Sunday, November 2, 2008

Grails Conditional Tags as Method Calls Trap - Part 2

In my previous post I was discussing how grails conditional tags should be used from the code. More or less post was about how to use conditional tags within if blog. Although I thought that my approach is good comment from Graeme Rocher opened my eyes. And therefore I decided to write short post because maybe this comment wasn't noticed by others.

I planned to write this post immediately next day but as I was busy with releasing first version of Flexible Feeds I didn't have enough time. By the way you can also visit :)

But let's go to the point. My approach with conditional tags was that if I want to execute something that depends on condition that is already implemented as tag you should use structure like this one:

if (g.conditionalTag() {true}) {
// execute some business logic

{true} part is actually closure that will get executed in the case that conditional tag satisfy condition. I must admit that this structure looks little bit strange but if I need not to copy/paste already existing code I am happy with that.

But as Graeme correctly noticed better approach in such situations would be:

g.conditionalTag() {
// execute some business logic

I agree that this is more readable and easier to understand.

In the case you need if...else approach then you still need version with the {true}.


Graeme Rocher said...

Typically when if/else is a requirement then you write the "else" version of the tag. For example in the JSecurity plugin:

jsec.hasRole(name:"Administrator") {
// do something
jsec.lacksRole(name:"Administrator") {
// do something else

jan said...

Yes, I use this approach when necessary in gsp pages but it seems to me little bit strange to provide else version of the tag just to easier use it from the code. Further more I am not sure if this would solve if..else if...else situations.