Search code examples
jsfcomponentscode-reuse

JSF 1.2 : Can I create reusable component inside JSF view


Is possible to something like this in jsf?

<ui:composition>
  <x:reusableCode id="editScreen">InnerHtml ... </x:reusableCode>
  code...
  <x:use component="editScreen"/>
</ui:composition

I know I can create my own component and register it in jsf tagLib, but I need reusable HTML only in on jsf view file.


Solution

  • In Facelets 1.x you can create a tag file for this purpose.

    Here's a basic kickoff example. Create /WEB-INF/tags/some.xhtml:

    <ui:composition 
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:ui="http://java.sun.com/jsf/facelets"
    >
        <h:outputText value="#{foo}" />
    </ui:composition>
    

    Define it in /WEB-INF/my.taglib.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE facelet-taglib PUBLIC
        "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
        "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
    
    <facelet-taglib>
        <namespace>http://example.com/jsf/facelets</namespace>
        <tag>
            <tag-name>some</tag-name>
            <source>/WEB-INF/tags/some.xhtml</source>
        </tag>
    </facelet-taglib>
    

    Register it in /WEB-INF/web.xml:

    <context-param>
        <param-name>facelets.LIBRARIES</param-name>
        <param-value>/WEB-INF/my.taglib.xml</param-value>
    </context-param>
    

    (note, when you have multiple, use semicolon ; to separate them)

    Finally just declare it in your main page templates.

    <ui:composition 
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:my="http://example.com/jsf/facelets"
    >
        <my:some foo="value1" />
        <my:some foo="value2" />
        <my:some foo="value3" />
    </ui:composition>
    

    A more advanced example can be found here: How to make a grid of JSF composite component? Note: JSF 2.0 targeted, but with minor changes based on above example it works as good on Facelets 1.x.