Java 在 thymeleaf 中为变量名称设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20728660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:49:57  来源:igfitidea点击:

setting up a value for a variable name in thymeleaf

javahtmlspringjspthymeleaf

提问by Deepak Ramakrishnan Kalidass

I am new to Thymeleaf and converting my Web page from JSP to Thymeleaf. I have a strut tag like this:

我是 Thymeleaf 的新手,正在将我的网页从 JSP 转换为 Thymeleaf。我有一个像这样的支柱标签:

<c:set var="someVariable" value="${someValue}"/>

That variable can be used anywhere in JSP. Is there any such alternatives for this in Thymeleaf?

该变量可以在 JSP 中的任何地方使用。在 Thymeleaf 中是否有这样的替代方案?

采纳答案by Sotirios Delimanolis

You can use local variables.

您可以使用局部变量

Declare an HTML element with a th:withattribute. For example

声明一个带有th:with属性的 HTML 元素。例如

<div th:with="someVariable=${someValue}">

The documentation states

该文件指出

When th:withis processed, that [someVariable]variable is created as a local variable and added to the variables map coming from the context, so that it is as available for evaluation as any other variables declared in the context from the beginning, but only within the bounds of the containing tag.

th:with被处理时,该[someVariable]变量被创建为局部变量并添加到来自上下文的变量映射中,以便它与从一开始就在上下文中声明的任何其他变量一样可用于评估,但仅限于包含标签。

回答by Alexandre Roger

Just a note, if you wish to assign more than one variable, separate them with a comma :

请注意,如果您希望分配多个变量,请用逗号分隔它们:

<div th:with="someVariable=${someValue},anotherVariable=${anotherValue}">

See the third example : Local Variable section of Thymeleaf documentation

参见第三个例子:Thymeleaf 文档的局部变量部分

回答by Vinci Da

  1. declare with th:with="varName=${'str'}

  2. ref with in src th:src="@{${varName}}"

  3. in more detail:

  1. 声明 th:with="varName=${'str'}

  2. 在 src 中引用 th:src="@{${varName}}"

  3. 更详细地:

<head th:with="component =${'/static/component'}, bizJs = ${'/static/js/biz'}">
    <span th:text="${component}"></span>
    <script th:src="@{(${component})}"></script>
    <script th:src="@{${bizJs} + '/static/js'}"></script>
</head>