Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf: show text if the attribute and property exists

Is there a simple way in thymeleaf to show the content of an attribute property if the property and the attribute exist? If there's an attribute "error" with a property "summary" in my html page, I'd like to show it:

<span th:text="${error.summary}">error summary</span>

If there is no attribute "error" the following error is raised:

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'summary' cannot be found on null

Currently I'm using the following approach, which just seems too complicated.

<span th:if="${error != null and error.summary != null}"><span th:text="${error.summary}">error summary</span></span>

Is there a simpler way to achieve that?

like image 431
James Avatar asked Feb 03 '14 13:02

James


People also ask

How do you check condition in Thymeleaf?

Using Switch Case Statement - th:switch Attribute To achieve similar to if-else condition in Thymeleaf , we can use th:switch attribute. Thymeleaf at the first step will evaluate ${condition} expression and if the value is true it will print p tag with TRUE text.

What is #{} in Thymeleaf?

Variable expressions are OGNL expressions –or Spring EL if you're integrating Thymeleaf with Spring. *{} is used for selection expressions. Selection expressions are just like variable expressions, except they will be executed on a previously selected object. #{} is used for message (i18n) expressions.

How do I get a request attribute in Thymeleaf?

Another way of accessing request parameters in thymeleaf is by using #httpServletRequest utility object which gives direct access to javax. servlet. http. HttpServletRequest object.

What is #fields in Thymeleaf?

Thymeleaf provides a special attribute th:field responsible for binding input fields with a property in the bean class. This attribute behaves differently depending on whether it is attached to. Thymeleaf supports all-new input types introduced in HTML5 such as type="color" or type="datetime" .


1 Answers

Sure! Since the processor associated with the th:if attribute has a higher precedence than the one associated with the th:text attribute, it will be evaluated first. Thus you can write:

<span th:if="${error != null && error.summary != null}" th:text="${error.summary}">Static summary</span> 

You could even shorten it using:

<span th:text="${error?.summary}">Static summary</span> 

But I think in this case, whether the summary exist or not, the span tag will be created, which is a bit ugly.

See more info about conditional expressions here.

like image 148
tduchateau Avatar answered Oct 05 '22 10:10

tduchateau