Search code examples
thymeleaf

th:with what is the difference between the two examples


<p th:with="firstName1='James1'">
        <p>Upper</p><p th:text="${firstName1}"></p>
</p>

<p th:with="df='today'">
        Today is: <span th:text="${df}">13 February 2011</span>

enter image description here

Could you tell me what is the difference between the two code sections. They seem identical for me. But there is some difference as the results differ.


Solution

  • Alright, I've never encountered this before... but it looks like Thymeleaf is enforcing the rule that Any <p> (or other block-level element) will implicitly close any open <p>. This works, for example:

    <div th:with="firstName1='James1'">
      <p>Upper</p>
      <p th:text="${firstName1}"></p>
    </div>
    
    <p th:with="df='today'">
      Today is: <span th:text="${df}">13 February 2011</span>
    </p>
    

    In your example, the firstName1 variable is out of scope because the parser is treating your HTML like this (so firstName1 is considered null):

    <p th:with="firstName1='James1'"></p>
    <p>Upper</p>
    <p th:text="${firstName1}"></p>