July 6th, 2011
5:16 pm
Facelets–using a custom tag interchangeably instead of a Decorator

Posted under JSF
Tags , , ,

Update 26/7/2011

Some more points that were omitted or incorrect in the first posting:-

  • A handy feature with templates/custom tags is that you can render children of the template/tag at the call site simply by using a <ui:insert> without a name. You therefore do not need to use a <ui:define> tag in this case, and all children which are not contained in other <ui:define> or <ui:param> tags will be rendered as part of this default <ui:insert>
  • The statement below that it is not possibly to insert a number of different markup variants in a composite component is incorrect. A composite component can have a number of named facets just like a ‘real’ JSF component, and these allow markup to be inserted in the same way as <ui:insert>/<ui:define> does for a template or custom tag.

Original Post

I had a complex decorator which was used for tree browsing. It had a number of ui:inserts for custom markup, plus also a large number of <ui:params> to define EL parameters used within it.

This all worked fine, and even looked quite tidy as all the <ui:params> were listed one per line below each other. However, it was all rather verbose compared to using a custom tag where you would use attributes instead to pass the EL parameters.

It turns out that you can convert a decorator to be a custom tag with no effort as they operate similarly. You merely need to register the xhtml file in a taglib as with any custom tag, and you can then call exactly the same code as a custom tag instead of a decorator.

The neat tricks here are that:-

  • <ui:params> become attributes which are less verbose, but the tag itself does not know any difference and needs no changes.
  • <ui:insert>/<ui:define> work perfectly with a custom tag exactly as they do with a decorator.

 

Another nice point on this is you can develop custom tags that include pseudo ‘child markup’ in similar fashion to composite components, by using the <ui:define>s. Providing you do not need the other features of composite components such as retargeting, Ajax etc., custom tags can be very useful where you have a need to insert a number of different markup variants for different flavours of the tag, as you cannot do this so flexibly with a composite component.

The technique of using <ui:inserts> in a custom tag is hinted at somewhat obliquely in Core Javaserver Faces, 3rd Edition, on P196 in the listing of the planet custom tag, which contains a <ui:insert> called content1.

No Comments »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.