Reputation: 2832
I'm looking for a cleaner way to write such jsp snippet:
<a href="${model.link}" class="button"<c:if test="${not empty model.title"> title="${model.title}"</c:if>>
This code is hard to read. The problem is, that there shouldn't be generated empty title=""
tag attribute, so this part have to be iffed.
I've found <c:out>
tag with it's default value attribute, however:
<c:out value='title="${model.title}"' default=""/>
won't work fine, cause value won't be null ever (since it is safe String concat).
Is there any way to write such easy stuff shorter, cleaner, better?
Upvotes: 1
Views: 414
Reputation: 3078
<c:if test = "${not empty model.title}">
<c:set var = "title" value = "title = '${model.title}'"/>
</c:if>
<a href="${model.link}" class="button" ${title}>
You could also do a custom taglib, so you'd end up with something like this:
<my:link class = "button" model = "${model}">...</my:link>
Since servlet spec somthing-rather you could implement the taglib as a jsp-snippet or you could go all the way using Java.
Upvotes: 1
Reputation: 3161
Another approach is as such;
<a href="${model.link}" class="button"<% if (model.title != null) { %> title="${model.title}"<% } %>>
a bit shorter than your first example, but still a bit too cluttering.
Bare in mind however, that your title still needs to be sanitized, since its encapsulated in a html tag.
StringEscapeUtils.escapeHtml(mode.title)
Upvotes: 1