Embed JavaScript in JSF Facelets
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:
or
Because Facelet is strict XML, therefore,
There are several ways to deal with this:
<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:
- Do not embed JS code directly in the page. Put the code in
.jsfiles and include it in the page with thesrcattribute. - Put JS code in a CDATA section:
<h:outputScript target="head"> <![CDATA[ document.write("<!-- this will render in the head tag -->"); ]]> </h:outputScript>
- Use XML entities:
<script type="text/javascript"> // jQuery code to append a div $('body').append('<div>Trailer div</div>'); </script>