Thymeleaf/Spring MVC - How do you nest variables/expressions in a Link expression?

情到浓时终转凉″ 提交于 2019-11-27 23:53:21

问题


For example, my controller method in Spring does this:

model.addAttribute("view_name", "foobar")

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" />

So it's not replacing the ${view_name} like I'm expecting.

What am I doing wrong? In general, how do you nest expressions like that in Thymeleaf?


回答1:


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

Literal substition (preferred method)

You can do literal substitions in a String with the pipeline syntax (|).

<link th:href="@{|/resources/libs/css/${view_name}.css|}" rel="stylesheet" />

String concatenation

<link th:href="@{'/resources/libs/css/' + ${view_name} + '.css'}" rel="stylesheet" />


来源:https://stackoverflow.com/questions/22059314/thymeleaf-spring-mvc-how-do-you-nest-variables-expressions-in-a-link-expressio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!