Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: Templates vs TagLibs. [closed]

In Grails, there are two mechanisms for modularity in the view layers: Template and TagLib.

While I am writing my own Grails app, I am often facing the same question when I need to write an UI component: do I need to use a template or a TagLib?

After searching the web, I didn't find a lot of best practices or rules of thumb concerning this design decision, so can you help me and tell me:

  1. What is the main difference between the two mechanisms?
  2. In which scenarios, do you use a TagLib instead of a Template (and vice-versa) ?
like image 441
fabien7474 Avatar asked Nov 16 '09 16:11

fabien7474


1 Answers

There is definitely some overlap, but below are several things to think about. One way to think about it is that Template is like a method-level reuse, while TagLibs are more convenient for API-level reuse.

  • Templates are great for when you have to format something specific for display. For example, if you wan to display a domain object in a specific way, typically it's easier to do it in a template, since you are basically just writing HTML with some . It's reusable, but I think its reusability in a bit limited. I.e. if you have a template, you'd use it in several pages, not in hundreds of pages.

  • On the other hand, taglibs is a smaller unit of functionality, but one you are more likely to use in many places. In it you are likely to concatenate strings, so if you are looking to create a hundred lines of HTML, they are less convenient. A key feature taglibs allow is ability to inject / interact with services. For example, if you need a piece of code that calls up an authentication service and displays the current user, you can only do that in a TagLib. You don't have to worry about passing anything to the taglib in this case - taglib will go and figure it out from the service. You are also likely to use that in many pages, so it's more convenient to have a taglib that doesn't need parameters.

  • There are also several kinds of taglibs, including ones that allow you to iterate over something in the body, have conditional, etc - that's not really possible with templates. As I said above, a well-crafted taglib library can be used to create a re-usable API that makes your GSP code more readable. Inside the same *taglib.groovy you can have multiple tag definitions, so that's another difference - you can group them all in once place, and call from one taglib into another.

Also, keep in mind that you can call up a template from inside a taglib, or you can call taglibs withing templates, so you can mix and match as needed.

Hope this clears it up for you a bit, though really a lot of this is what construct is more convenient to code and how often it will be reused.

like image 153
Jean Barmash Avatar answered Sep 21 '22 13:09

Jean Barmash