Embed JavaScript in JSF Facelets 

Joined:
08/13/2009
Posts:
164

November 28, 2011 21:04:15    Last update: November 28, 2011 21:04:15
Some innocent looking JavaScript may cause a fatal error in a Facelet page. For example:
<script type="text/javascript">
if (items.length < 10) {
    alert("less than 10 items found");
}
</script>

or
<script type="text/javascript">
// jQuery code to append a div
$('body').append('<div>Trailer div</div>');
</script>

Because Facelet is strict XML, therefore, < and > must be escaped.

There are several ways to deal with this:
  1. Do not embed JS code directly in the page. Put the code in .js files and include it in the page with the src attribute.
  2. Put JS code in a CDATA section:
    <h:outputScript target="head">
            <![CDATA[
              document.write("<!-- this will render in the head tag -->");
            ]]>
    </h:outputScript>
    

  3. Use XML entities:
    <script type="text/javascript">
    // jQuery code to append a div
    $('body').append('&lt;div&gt;Trailer div&lt;/div&gt;');
    </script>
    

Share |
| Comment  | Tags