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?
The Thymeleaf is a template engine that is used to create view pages in Spring MVC. It provides full Spring integration and was designed to replace JSP as a view page in Spring MVC. It is better to use Thymeleaf if you are working with a web application.
Spring beans. Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName syntax, for example: In the above example, @urlService refers to a Spring Bean registered at your context, e.g. This is fairly easy and useful in some scenarios.
ThymeleafViewResolver implements the ViewResolver interface and is used to determine which Thymeleaf views to render, given a view name. The final step in the integration is to add the ThymeleafViewResolver as a bean: 3. Thymeleaf in Spring Boot
Or by using #session, that gives you direct access to the javax.servlet.http.HttpSession object: $ {#session.getAttribute ('mySessionAttribute')} The ServletContext attributes are shared between requests and sessions. In order to access ServletContext attributes in Thymeleaf you can use the #servletContext. prefix:
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With