Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 311
trusktr Avatar asked Feb 27 '14 04:02

trusktr


People also ask

What is thymeleaf in Spring MVC?

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.

How do I access spring beans in thymeleaf?

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.

What is thymeleafviewresolver in Spring Boot?

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

How to access servletcontext attributes in thymeleaf?

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:


1 Answers

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" />
like image 58
Tom Verelst Avatar answered Sep 20 '22 13:09

Tom Verelst