“Thymeleaf – 在没有标签的情况下输出变量”

huangapple go评论139阅读模式
英文:

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(&quot;tester&quot;, &quot;hello&quot;);

and in html template I output:

&lt;span th:text=&quot;${tester}&quot;&gt;&lt;/span&gt;

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:

&lt;body&gt;
    &lt;th:block th:text=&quot;${tester}&quot;&gt;&lt;/th:block&gt;    
&lt;/body&gt;

This renders the following HTML:

&lt;body&gt;
    hello    
&lt;/body&gt;

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:

&lt;body&gt;
    &lt;th:block th:text=&quot;${tester}&quot;&gt;&lt;/th:block&gt;    
&lt;/body&gt;

This renders the following HTML:

&lt;body&gt;
    hello    
&lt;/body&gt;

Only the variable is displayed.

答案2

得分: 2

使用Thymeleaf表达式内联(文档)可以使用[[...]][(...)]。通过表达式内联,您无需使用合成标签。

示例:

&lt;body&gt;
tester的值为[[${tester}]]。
&lt;/body&gt;
英文:

Use Thymeleaf expression inlining (docs) using either [[...]] or [(...)]. With expression inlining, you do not need to use synthetic tags.

Example:

&lt;body&gt;
The value of tester is [[${tester}]].
&lt;/body&gt;

答案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

我还找到了一些解决方法:

&lt;span th:text=&quot;${tester}&quot; th:remove=&quot;tag&quot;&gt;&lt;/span&gt;

th:remove 移除了 span 标签,但保留内容。

英文:

I also managed to figure out some workaround:

&lt;span th:text=&quot;${tester}&quot; th:remove=&quot;tag&quot;&gt;&lt;/span&gt;

th:remove removes span tag, but preserves content.

huangapple
  • 本文由 发表于 2020年5月29日 14:54:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/62080295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定