Tony Tony - 6 months ago 675
Javascript Question

Thymeleaf th:text How to add static text to dynamic value

Started with Thymeleaf and have one question. I have iteration with

<tr th:each="it,row : ${res.answers}">
<td th:class="${row.even}? 'even' : 'odd'" th:text="${row.count}">
1
</td>
<td th:class="${row.even}? 'even' : 'odd'" th:text="${it.question}">
Value1
</td>
<td th:class="${row.even}? 'even' : 'odd'" th:text="${it.correctAnswer}">
col2
<a href="" th:onclick="'showExplanation(\'' + ${it.comment} + '\');'">
<sup>Explanation</sup>
</a>
</td>
<td th:class="${row.even}? 'even' : 'odd'" th:text="${it.answer}">
col3
</td>
</tr>


The line with
${it.correctAnswer}
is one that should be formatted as following:

If and only if there is not empty String in
${it.comment}
then it should be appended superscripted string "Explanation" and when we click this string some Javascript function is called.


My solution above obviously didn't work, but is there any way to add some static html code to dynamic value generated by Thymeleaf at runtime.

What I am trying to do is :

Image

Answer

In your example you require to concat text to link, to do it simply change your html from:

<td th:class="${row.even}? 'even' : 'odd'" th:text="${it.correctAnswer}">
 col2
 <a href="" th:onclick="'showExplanation(\'' + ${it.comment} + '\');'" >
  <sup>Explanation</sup>
 </a>
</td>

to

<td th:class="${row.even}? 'even' : 'odd'" >
 <span th:text="${it.correctAnswer}">col2</span>
 <a href="" th:if="${it.comment}!=''" th:onclick="'showExplanation(\'' + ${it.comment} + '\');'">
  <sup>Explanation</sup>
 </a>
</td>

This should display comments link when there are some.

Comments