setting up a value for a variable name in thymeleaf

JavaHtmlSpringJspThymeleaf

Java Problem Overview


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

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

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

Java Solutions


Solution 1 - Java

You can use local variables.

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

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

The documentation states

> When th:with is 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.

Solution 2 - Java

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

Solution 3 - Java

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

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

  3. in more detail:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeepak Ramakrishnan KalidassView Question on Stackoverflow
Solution 1 - JavaSotirios DelimanolisView Answer on Stackoverflow
Solution 2 - JavaAlexandre RogerView Answer on Stackoverflow
Solution 3 - JavaVinci DaView Answer on Stackoverflow