Thymeleaf/Spring MVC-如何在链接表达式中嵌套变量/表达式? [英] Thymeleaf/Spring MVC - How do you nest variables/expressions in a Link expression?
问题描述
例如,我在Spring中的控制器方法就是这样做的:
For example, my controller method in Spring does this:
model.addAttribute("view_name", "foobar")
我正在尝试在我的Thymeleaf模板中做到这一点:
And I'm trying to do this in my Thymeleaf template:
<link th:href="@{/resources/libs/css/${view_name}.css}" rel="stylesheet" />
但是渲染的结果是这样的:
But the rendered result is this:
<link href="/app/resources/libs/css/${view_name}.css" rel="stylesheet" />
所以它并没有像我期望的那样取代${view_name}
.
So it's not replacing the ${view_name}
like I'm expecting.
我做错了什么?一般来说,如何在Thymeleaf中嵌套这样的表达式?
What am I doing wrong? In general, how do you nest expressions like that in Thymeleaf?
推荐答案
由于您未使用表达式(例如${...}
,#{...}
,|...|
,__...__
,'quoted string'
, ...),Thymeleaf会将整个表达式视为String
,而不执行任何内部表达式.
Since you are not starting the url rewrite with an expression (e.g. ${...}
, #{...}
, |...|
, __...__
, 'quoted string'
, ...), Thymeleaf will consider the whole expression as a String
and not execute any of the inner expressions.
以下示例将起作用,因为它以表达式开头.
The following example would work because it starts with an expression.
@{${attribute}}
对于您的示例,您具有以下可能性
For your example you have the following possibilities
文学替代(首选方法)
您可以使用管道语法(|
)在String
中进行文字替换.
You can do literal substitions in a String
with the pipeline syntax (|
).
<link th:href="@{|/resources/libs/css/${view_name}.css|}" rel="stylesheet" />
字符串串联
<link th:href="@{'/resources/libs/css/' + ${view_name} + '.css'}" rel="stylesheet" />
这篇关于Thymeleaf/Spring MVC-如何在链接表达式中嵌套变量/表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!