How to set a global variable in thimeleaf?

I use thymeleaf in an interface and I know the concept of variable in thymeleaf

 <span th:with="var=${someValue}" th:text="${var}"></span> 

if I use th:text , the value in the variable will be printed, and I can use this variable in the same element. Is there a way to use var in another element like

 <span th:with="var=${someValue}"></span> <span th:text="${var}"></span> 

I need to provide the global scope this variable, is this possible in the timeline?

+6
source share
3 answers

Define var in the body tag that opens

 <body th:with="var=${var_value}"> 
+5
source

The head variable is not supported in the timeline, but it can be achieved using the built-in javascript.

  • Thymeleaf var_value is stored in the javascript 'value' variable and sets the value in the input field using jQuery.

 <script th:inline="javascript"> /*<![CDATA[*/ $(document).ready(function (){ var Value = /*[[${var_value}]]*/ ''; $("#ID").val(Value); }); /*]]>*/ </script> 
  <input type="text" class="order-entry" id="ID" placeholder="" th:value="${''}" /> 
+1
source

Only a nested element can see the variable. The div tag is just an example. You can use the tags you want

 <div th:with="var=${var_value}"> inside div tag var is visible. </div> 
-one
source

All Articles