Search code examples
springthymeleafspring-el

How to interpolate variables into 'then' expressions


I'm trying to do create a thymeleaf fragment that behaves like the following:

<section th:fragment="alert(type)" th:class="${type ? 'alert-' + type : ''}"></section>
<div th:replace="alert(info)"></div>
<section class="alert-info"></section>

I've tried interpolation |alert-${type}|, and concatenation 'alert-' + type, but I can't get it working. Any suggestions?


Solution

  • In the Thymeleaf fragment, add a null check:

    <section th:fragment="alert(type)" 
             th:class="${type != null ? 'alert-' + type : ''}">
    </section>
    

    Optionally, I prefer to put literals into single quotes, just for clarity. And when passing values to fragments, I also prefer to use the parameter names (again, this is optional).

    In the following examples, the alert_fragment.html is my test fragment.

    <div th:replace="alert_fragment.html :: alert(type='info')"></div>
    

    And for the null case:

    <div th:replace="alert_fragment.html :: alert(type=null)"></div>
    

    If you are passing the type value from the server, then it would be something like this, of course:

    <div th:replace="alert_fragment.html :: alert(type=${info})"></div>
    

    The resulting HTML:

    <body>
        <section class="alert-info"></section>
        <section></section>
    </body>
    

    Update

    If the alert type will never be null, then you can simplify the fragment to this:

    <section th:fragment="alert(type)" th:class="'alert-' + ${type}"></section>