en Lopes
en Lopes

Reputation: 2153

Thymeleaf: combining literals with variables

I have this piece of code in Thymeleaf:

<tr th:each="image: ${images}" >
    <img th:onmouseover="'javascript:imageName(\'theImageName\' + ${image.id} +'\');'"> 
</tr>

but I got a parsing error

Upvotes: 2

Views: 2603

Answers (4)

Mike Patrick
Mike Patrick

Reputation: 11006

I have two observations:

Open Tag?

Some Thymeleaf template modes require that the template be well-formed. If this is the case, any unclosed img tag will result in a parsing error.

When this happens, the java stack trace is informative:

org.xml.sax.SAXParseException: The element type "img" must be terminated by the matching end-tag "</img>".

but the error you may see in the browser isn't:

Exception parsing document: template="home", line 19 - column 6

My minimally configured Spring Boot app defaults to one of these stricter modes (HTML5? XML?), so both @Metroids' and @ErikMD's answers give me a parsing error as they are, but both work if I close the image tags.

If this isn't the case for you, updating the question with the java stack trace might help.

Pipes

I think all these apostrophes and plus signs make the markup difficult to read (and write). Using literal substitutions with pipes is arguably more legible (and less error-prone):

<img th:onmouseover="|javascript:imageName('ImageName${image.id}');|" />

or even:

<img th:onmouseover="|imageName('ImageName${image.id}')|" />

If you don't like this approach, the code in your question can also be fixed by removing the backslash after theImageName:

<img th:onmouseover="'javascript:imageName(\'theImageName' + ${image.id} +'\');'" />

Upvotes: 3

ErikMD
ErikMD

Reputation: 14763

Could you try the following code instead?

<img th:attr="onmouseover=${'javascript:imageName(''theImageName' + image.id + ''');'}">

This answer was inspired by that other SO answer and the relevant section of the Thymeleaf documentation is 5.1: Setting the value of any attribute.

Upvotes: 0

Metroids
Metroids

Reputation: 20487

I'd format it like this:

<tr th:each="image: ${images}" >
    <img th:onmouseover="${'javascript:imageName(''theImageName' + image.id + ''');'}"> 
</tr>

Upvotes: 1

Periklis Douvitsas
Periklis Douvitsas

Reputation: 2491

can you try the following

<img th:onmouseover="'javascript:imageName(\''+ theImageName\' + ${image.id} +'\');'"> 

Upvotes: 1

Related Questions