Adding a class to html element conditionally with grails tags

Robin Jamieson picture Robin Jamieson · Nov 20, 2009 · Viewed 7k times · Source

With tags, you can do this in a gsp:

<g:if test="${someBean?.aCondition}">
  <div class="aSection">
  ...
  </div>
</g:if>

What I really want to do is add a second 'class' that either contains the 'display:none' or 'display:block' attributes based the value of '${someBean?.aCondition}'.

The final html would like this:

<div class="aSection hiddenItem">
...
</div>

(the div would have 'shownItem' for its class if ${someBean?.aCondition} is true)

The corresponding css:

.shownItem
{
  display: block;
}
.hiddenItem
{
  display: none;
}

What's a good way to achieve this?

Answer

billjamesdev picture billjamesdev · Nov 20, 2009

Easy enough:

<div class="aSection ${someBean?.aCondition ? 'shownItem':'hiddenItem'}">
...
</div>

You can use ${} blocks inside html attributes, no problem, just be sure not to use any double-quotes in your expression block, as that confuses things.