Sunday, April 19, 2009

Facelets Tutorial : UI Param Tag

<< Previous        Next>>

UI Param Tag

In our previous facelets tutorial on ui :component, the Backing Bean variable 'menus' is directly referenced in the sideMenu.xhtml file. This make the sideMenu.xhtml non-reusable.  If we could pass the 'menus' object to the sideMenu.xhtml as a variable from the home.xhtml, that will make sideMenu.xhtml more reusable.  This can be achieved with the help of the Facelets tag ui : param. The ui : param tag is used to pass objects as named variables between Facelets.  The ui : param tag has two required attributes, name and value attributes. In this example we will modify the facelets pages  in our previous example to pass the object (menus) as a variable.

First we modify the sideMenu.xhtml to get rid of the Backing Bean reference. We could achieve this by replacing the value of the items attribute of c:forEach to '#{menus}'. This change assumes that the facelets using sideMenu.xhtml should pass the menus object using ui:param tag with the name attribute value set as 'menus'.

See the complete sideMenu.xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns=""
   This text will not be rendered.
      <c:forEach var="menu" items="#{menus}">
           <a href="#{menu.url}">#{menu.label}</a><br/>

Modified home.xhtml is shown below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns=""
<ui:composition template="WEB-INF/templates/insertTemplate.xhtml">
<ui:define name="sidemenu">
        <ui:include src="sideMenu.xhtml" >
        <ui:param name="menus" value="#{menuBackingBean.menus}"/>
<ui:define name="content">
        This is an example of a simple Facelets template.<br/>
        Here Header and Footer appears from template.(inserTemplate.xhtml)<br/>
        Side Menu appears from sideMenu.xhtml<br/>
        This section appears from templateClient.(home.xhtml)

Run your webapplication

To run your web application, right click on home.xhtml, click- >run as -> run on server.
Select the server type ,Apache Tomacat v6.0 Server.Click Fininsh.

Open a web browser and type the url : http://localhost:8080/JSFFaceletsExample/home.xhtml

Your page will be rendered like this:

You can also use this tag where a ui:define tag is used within ui:composition or ui:decorate tag. The name attribute of the ui : param tag should match the name attribute of a ui:define tag contained in a ui:composition or ui:decorate in the template page receiving the object.