Pages

Monday, November 05, 2012

JSF 2.x Tip of the Day: Using <ui:decorate/>, <ui:fragment/>, and <ui:include/>

We have been doing a lot of JSF work lately, and I was surprised that my team really did not have a really good grasp of mixing <ui:decorate/>, <ui:fragment/>, and <ui:include/>. These elements are very powerful and allow you to build more complex and reusable code.

The <ui:fragment/> is probably one of the most important elements in Facelets. The ability to use the rendered attribute to determine if the contained content should be displayed is one of the most important uses. Today, I see a lot of examples where you place some code in a <h:panelGroup/> element where you set the rendered attribute using an EL binding. This has the side effect of producing a <span/> element. If you add enough of them, you end up with spans inside spans inside spans... you get the idea.

The <ui:fragment/> has no side effects. You either produce (emit) the code you want, or nothing. A very clean process. The <ui:decorate/> component is one of the least most used and not very well understood. The <ui:decorate/> component is used to add additional functionality to a page. If any other template code is in the decorator page to be included, it is added to the page. In other words, it includes the other content on the page. For example, take a look at the code below for a decorated table. Note that the <table/> is included in the output. It is also outside of the <ui:decorate/> tag.

decoratedTable.xhtml


This was added to a page as you can see in the next snippet, and produced the image below.

DecoratedPage.xhtml



Finally, the <ui:include/> allows you to add content from another page into the current page. This inclusion mechanism allows you to take advantage of code that can be templated for reuse. In order to be complete, I will show the remaining code snippets from the examples above, as well as another example.

unorderedListTemplate.xhtml



listElements.xhtml



decoratedExample.xhtml



0 comments :