A simple GSP toolbar taglib for Grails
Did you ever had to implement a menu in Grails GSP where every link element should be seperated from its predecessor by a separator character and where some of the elements can be missing when certain conditions are not met (security etc)?
The part with the optional elements can turn the separator handling into a real mess. So today I decided to end this nonsense. The result is a tiny taglib which can be integrated into every grails project. The usage is pretty self explanatory:
<mx:toolbar separator=’|'>
<mx:item>
<shiro:hasPermission permission=”topic:delete”>
<g:link controller=”topic” action=”delete” id=”${topic.id}”><g:message code=”topic.delete”></g:message></g:link>
</shiro:hasPermission>
</mx:item>
<mx:item>
<shiro:hasPermission permission=”topic:lock”>
<g:link controller=”topic” action=”lock” id=”${topic.id}”><g:message code=”topic.lock”></g:message></g:link>
</shiro:hasPermission>
</mx:item>
</mx:toolbar>
And this would be rendered assuming the user has permission for both buttons:
<a href="/topic/delete/10">Delete</a>|<a href="/topic/lock/10">Lock</a> |
Tag Library Source:
class MenuTagLib { static namespace = 'mx' /** The toolbar container */ def toolbar = { attrs, body -> def separator = attrs.separator ?: '|' // we'll be using this to keep track of our items def menuItems = [] this.pageScope.menuItems = menuItems // this will execute the body, so that the items are appended obviously, // anything other than the item tags will not render correctly. body() // render every item and add a separator except for the last item menuItems.eachWithIndex { item, index -> out << item if(index < menuItems.size() - 1) out << separator } } /** A toolbar item */ def item = { attrs, body -> def itemContent = body().trim() if(itemContent) // only add the item if rendering evaluated to non-empty string this.pageScope.menuItems << itemContent } } |


