Thymeleaf Image SRC Example

By Arvind Rai, April 10, 2023
On this page, we will learn using image SRC in Thymeleaf application.
th:src : We can specify absolute, context-relative as well as server relative URL to load image. Use @{...} expression to specify URL. To resolve variables, use ${...} expression.
th:title : Specifies title for image. To resolve variables, use ${...} expression.
th:alt : Specifies alt for image. To resolve variables, use ${...} expression.

Absolute URL

Image with absolute URL.
<img th:src="@{https://www.concretepage.com/images/favicon.png}" 
             th:title="${myPage.imageTitle}" th:alt="${myPage.imageTitle}"/> 
Output
<img src="https://www.concretepage.com/images/favicon.png" 
		             title="ConcretePage" alt="ConcretePage"/> 

Context-relative URL

Image with context-relative URL.
<img th:src="@{/images/cplogo.jpg}" 
           th:title="${myPage.imageTitle}" th:alt="${myPage.imageTitle}"/> 
Output
<img src="/cp/images/cplogo.jpg" 
           title="ConcretePage" alt="ConcretePage"/> 

Server-relative URL

We can load images from different application in the same server as following.
<img th:src="@{~/otherApp/images/cplogo.jpg}" 
           th:title="${myPage.imageTitle}" th:alt="${myPage.imageTitle}"/> 
Output
<img src="/otherApp/images/cplogo.jpg" 
           title="ConcretePage" alt="ConcretePage"/> 

Using Variables

Find the code to use variables. Variables are used with${...} expression.
Ex-1
<img src="abc.png" th:src="@{'/images/'+${myPage.imageName}}" 
              th:title="${myPage.imageTitle}" th:alt="${myPage.imageTitle}"/> 
Ex-2
<img th:src="@{${myPage.imageDir} + '/' + ${myPage.imageName}}" 
           th:title="${myPage.imageTitle}" th:alt="${myPage.imageTitle}"/> 

Using th:attr

For src, title and alt, we can also use th:attr attribute. Find the example.
<img src="abc.png" th:attr="src=@{'/images/'+${myPage.imageName}},
	                  title=${myPage.imageTitle},alt=${myPage.imageTitle}" /> 

Reference

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us