英文:
Thymeleaf - output variable without a tag
问题
我使用Thymeleaf作为模板引擎,通常像这样输出变量值:
在Java中,我设置:
ctx.setVariable("tester", "hello");
然后在HTML模板中,我输出:
<span th:text="${tester}"></span>
这个方法效果很好,但我想在不需要标签的情况下输出一个变量。像下面这样的方式会很好:
${tester}
不幸的是,这并不起作用。我的目标是避免使用不必要的标签来输出变量值。在Thymeleaf中能实现这一点吗?
英文:
I use Thymeleaf as a templating engine and I usually output variable value like this:
in Java I set:
ctx.setVariable("tester", "hello");
and in html template I output:
<span th:text="${tester}"></span>
This works great, but I would like to output a variable without the need of a tag. Something following would be great:
${tester}
Unfortunately it does not work. My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?
答案1
得分: 6
My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?
Yes this is possible. You can use the Thymeleaf synthetic th:block
tag (see here).
Example template excerpt:
<body>
<th:block th:text="${tester}"></th:block>
</body>
This renders the following HTML:
<body>
hello
</body>
Only the variable is displayed.
英文:
My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?
Yes this is possible. You can use the Thymeleaf synthetic th:block
tag (see here).
Example template excerpt:
<body>
<th:block th:text="${tester}"></th:block>
</body>
This renders the following HTML:
<body>
hello
</body>
Only the variable is displayed.
答案2
得分: 2
使用Thymeleaf表达式内联(文档)可以使用[[...]]
或[(...)]
。通过表达式内联,您无需使用合成标签。
示例:
<body>
tester的值为[[${tester}]]。
</body>
英文:
Use Thymeleaf expression inlining (docs) using either [[...]]
or [(...)]
. With expression inlining, you do not need to use synthetic tags.
Example:
<body>
The value of tester is [[${tester}]].
</body>
答案3
得分: 1
Thymeleaf触发在"th:"标签上,据我所知,这是唯一的方式。
您描述的行为适用于JSF。
最好的问候
Ben
英文:
Thymeleaf triggers on the "th:" tag and as far as I know thats the only way.
The behaviour you describe works with JSF.
Best regards
Ben
答案4
得分: 1
我还找到了一些解决方法:
<span th:text="${tester}" th:remove="tag"></span>
th:remove 移除了 span 标签,但保留内容。
英文:
I also managed to figure out some workaround:
<span th:text="${tester}" th:remove="tag"></span>
th:remove removes span tag, but preserves content.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论