Search code examples
thymeleafbootstrap-5

Thymeleaf don´t work with bootstrap badges?


I'm trying to use Bootstrap (v5.3) Badges.

When I use the example of docs:

<button type="button" class="btn btn-primary position-relative">
  Inbox
  <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
    99
  </span>
</button>

it works perfectly. But, if I replace the 99 with a thymeleaf portion, that didn't work.

<button type="button" class="btn btn-primary position-relative">
  Inbox
  <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
    ${numberDependents}
  </span>
</button>

I've tried many ways:

${numberDependents}
__${numberDependents}__
[[${numberDependents}]]
<span th:text="${numberDependents}"></span>
<span th:text="|${numberDependents}|"></span>
<span th:text="__${numberDependents}__"></span>
<span th:text="[[${numberDependents}]]"></span>

And no one worked... any suggestions?


Solution

  • Bootstrap is the client-side framework that styles your HTML content on the client, in the browser. Thymeleaf is the server-side rendering library and we use it to render HTML that will be sent to the client-side. Those are two different technologies that are not related to each other.

    If your Bootstrap static example works fine in the browser, this means you are done with Bootstrap and the badges are working properly. Period. No more relation to Bootstrap, just a plain HTML with some style classes from Bootstrap.

    Next, you would like to make the number in the badge driven by server-side logic and this is on Thymeleaf's shoulders to generate HTML you need. The correct HTML template for Thymeleaf parsing should/may look as follows...

    <button type="button" class="btn btn-primary position-relative">
      Inbox
      <span th:text="${numberDependents}" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
        99
      </span>
    </button>
    

    In this example, I have copied your "working" HTML that properly displays Bootstrap badge and added th:text attribute to the span tag for Thymeleaf to process it before this HTML will be sent to the client.

    Now, as I see you mention above that you have tried this. In this case, you have an issue with ${numberDependents} variable. Or it is not available (for example controller didn't set it), or there is a spelling mistake or something else. I cannot tell as I don't have the controller's code. Also, you didn't mention that your Thymeleaf processing engine works fine with yet another variable/page. See/debug server-side errors for it.