Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

spring - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...