Plugins: fleegix.ejs
Embed JavaScript in client-side HTML templates with the familiar <% %> tags.
Overview
The fleegix.ejs.Template object allows you to use snippets of HTML as templates in your client-side code.
Rather than inventing yet another language just for the templates, fleegix.ejs uses plain JavaScript as an embedded scripting language directly in your templates. This approach should be familiar to anyone who has used PHP, Ruby's ERB, etc.
As you might expect, code in <% %> tags is simply executed. Code in <%= %> tags is executed and any result is added to the output.
Usage
Template objects are instantiated like so:
var str = '<p>Howdy, <%= dudesName %></p>.';
var templ = new fleegix.ejs.Template({ text: str });
You can provide template text from three different sources:
- text -- A simple string of template text.
- node -- A textarea element containing template text.
- url -- The URL for a text file on the Web server containing template text.
Some other examples:
// Use a text node as the source
var elem = document.getElementById('templateTextArea');
var templ = new fleegix.ejs.Template({ node: elem });
// Use a text file on the server
var templ = new fleegix.ejs.Template({ url:
'/some_template.html.ejs' });
You can then use your shiny new template by calling the
process method, passing it data and the DOM
node you want to insert the template results into:
// Create a new node
var node = document.createElement('div');
// Data to use in the template
var templData = { dudesName: 'Geddy' };
// Execute the template and insert the text into
// the DOM node
var templ.process({ domNode: node, data: templData });
alert(node.innerHTML); // Alerts "<p>Howdy, Geddy.<p>"
Tags
The fleegix.ejs templates recognize the same set of tags as Ruby's ERB templates:
- <% %> -- Executes the code in the tags.
- <%= %> -- Executes the code in the tags, appends any result to the output.
- <%# %> -- Comments -- does nothing.
- <%% %> -- Inserts literal <% %> tags.