Shklyar
Shklyar

Reputation: 160

Thymeleaf #strings.replace with regex and th:fragment

I have persisted entity with field text. Inside text I have part to replace. myEntity.text:

some text
twoImages[12_v13.PNG, 10_v6.PNG]
text text text
twoImages[12_v13.PNG, 10_v6.PNG]
<h1>And HTML</h1>

So in view I want to use something like th:utext. But with replaced images blocks with th:fragment (~15 lines per fragment).

Output should be like this:

some text
<img .. 12_v13.PNG />
<br />
<img .. 12_v13.PNG />
<additional html />
text text text
<img .. 12_v13.PNG />
<br />
<img .. 12_v13.PNG />
<additional html />
<h1>And HTML</h1>

How to realize this with Thymeleaf?

Upvotes: 0

Views: 1155

Answers (1)

dimirsen Z
dimirsen Z

Reputation: 891

If the entire text of the field is a single string, you will have to parse it using regex matcher or some generated parser. Say [12_v13.PNG, 10_v6.PNG] has to be parsed e.g. with \\[([^,]),\\s([^\\]]*)] The first group will give 12_v13.PNG, the second one - 10_v6.PNG.

You need to provide the path to each of the images in src property of img tag. You can achieve the result this way:

<img th:src="@{/images/test.png}" /> 

It is implied, that /images folder is within webapp folder of your project.

<img th:src="@{/resources/images/Picture.png}" />

Output as:

<img src="/resources/image/Picture.png" />

When you hit http://localhost:8080/myapp/resources/images/Picture.png in you browser then you should be able to access the image for the above syntax to work.

This link is useful: Standard URL Syntax

Please have a look at my thymeleaf demo project: demo project (the folder with templates will get opened) You'll find data on project structure and examples of thymeleaf templates.

Upvotes: 1

Related Questions