g:truthLink – taglib for optionally rendering a link based on groovy truth

Very often, there are requirements in the UI to render a link only when some conditions are met. You want to disable the link if the item is selected, not in use, etc.

Using just gsp tags, you would do something like this:

<g:if test="${ someCondition }"><g:link action="blah"></g:if>someBodyCode<g:if test="${ someCondition }"></a> </g:if>

or

<g:if test="${ someCondition }">
    <g:link action="blah"> someBodyCode </g:link>
</g:if>
<g:else>
     someBodyCode
</g:else>

Neither of these approaches is very elegant since it forces you to either repeat the content block or the conditional block.

With grails tags, we can write our own link taglib that supports passing an optional truth parameter. It looks like this:

   <g:truthLink test="${somecondition}" action="blah"> someBodyCode </g:truthLink>

and the tag library is ridiculously simple:

class TruthLinkTagLib {
	def truthLink = { attrs, body ->
		if( attrs['test'] )
			out << g.link( attrs, body )
		else
			out << body()
	}
}

This keeps things simple and you can pass in any additional parameters you would pass into g:link.

Hope that helps,

The truthlink will set you free…

6 thoughts on “g:truthLink – taglib for optionally rendering a link based on groovy truth

  1. Pingback: Test Link « IntelliGrape Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s