se lazy loading to ensure the JS is only added the // first time this method is called. if (headElements == null) { // Get the head elements from the super implementation headElements = super.getHeadElements(); JsScript jsScript = new JsScript("alert('Hello World!);"); headElements.add(jsScript); } return headElements; } } The
jsScript instance will be rendered as follows:
<script type="text/javascript"> alert('Hello World'); </script>
Below is an example showing how to render inline Javascript from a Velocity template.
First we create a Velocity template
(/js/mycorp-template.js) which contains the variable
$divId that must be replaced at runtime with the real Div ID attribute:
hide = function() { var div = document.getElementById('$divId'); div.style.display = "none"; }
Next is the Page implementation:
public class MyPage extends Page { public List getHeadElements() { // We use lazy loading to ensure the JS is only added the // first time this method is called. if (headElements == null) { // Get the head elements from the super implementation headElements = super.getHeadElements(); // Create a default template model to pass to the template Map model = ClickUtils.createTemplateModel(this, getContext()); // Add the id of the div to hide model.put("divId", "myDiv"); // Specify the path to the JavaScript template String templatePath = "/js/mycorp-template.js"; // Create the inline JavaScript for the given template path and model JsScript jsScript = new JsScript(templatePath, model); headElements.add(jsScript); } return headElements; } }
The
jsScript instance will render as follows (assuming the context path is
myApp):
<script type="text/javascript"> hide = function() { var div = document.getElementById('myDiv'); div.style.display = "none"; } </style>
Character data (CDATA) support
Sometimes it is necessary to wrap
inline {@link JsScript JavaScript}in CDATA tags. Two use cases are common for doing this:
- For XML parsing: When using Ajax one often send back partial XML snippets to the browser, which is parsed as valid XML. However the XML parser will throw an error if the content contains reserved XML characters such as '&', '<' and '>'. For these situations it is recommended to wrap the script content inside CDATA tags.
- XHTML validation: if you want to validate your site using an XHTML validator e.g: http://validator.w3.org/.
To wrap the JavaScript content in CDATA tags, set {@link #setCharacterData(boolean)} to true. Below is shown how the JavaScriptcontent would be rendered:
<script type="text/javascript"> /∗<![CDATA[∗/ if(x < y) alert('Hello'); /∗]]>∗/ </script>
Notice the CDATA tags are commented out which ensures older browsers that don't understand the CDATA tag, will ignore it and only process the actual content.
For an overview of XHTML validation and CDATA tags please see
http://javascript.about.com/library/blxhtml.htm.