Search code examples
thymeleafspring-thymeleaf

How to create Thymeleaf button with image on it?


I am creating my website https://github.com/iva-nova-e-katerina/mysite_v2 (actually migrating from JSF to Spring MVC) And want to create a button with image on it

<th:button type="button" th:image="@{/dist/images/ru32x32.png}" onclick="window.location.replace('?lang=ru');"/>

But it doesn't work. Image is not appears. In the same time image is here http://localhost:8080/dist/images/ru32x32.png displays well. Please teach me how to properly create button with image in Thymeleaf?


Solution

  • Thymeleaf doesn't know or care about images with buttons on them. It only knows about HTML.

    1. <th:button /> isn't a valid HTML (or Thymeleaf) tag. You should be using <button /> here.
    2. The <button /> element does not have an attribute image.

    If you want a button with an image, you should create the HTML you want and style it the way you want first, and then add the Thymeleaf if applicable.

    <button type="button" onclick="window.location.replace('?lang=ru');">
      <img th:src="@{/dist/images/ru32x32.png}" />
    </button>