Easy EJS
I have recently took up the Embedded Javascript jQuery plugin again. It is a templating engine for javascript. (here) It is also part of the javascriptMVC framework. However I was not happy with the way you call the render function everytime you need to render a view.
$('header').html(new EJS({url: "templates/header"}).render());
So I developed my own solution where you only need to add a classname of 'view' to an element. And if you name your templates according to convention- it should render out the template. (in this case header.ejs)
<div id="header" class="view"></div>
You can also override the template name like so
<div id="header" class="view myheader"></div>
Just append the template name to the classname. Here is the code- you need references to jQuery and EJS for this to work. Just have the script execute right after page load.
function render_views()
{
var Views = []; var templatePath = "templates/"
// Find me some elements with a view class attached
$('.view').each(function() {
var arg;
var id = $(this).attr("id");
// See if there is a template overide present- split the
// class into an array.
arg = $(this).attr("class").split(" ");
var customView;
// So only the second value becomes the argument to overide-
// I see an error in my assumptions though. Can you see it? will fix
// that sometimes. (hint: what if you have more then one class
// definitions per element?)
if (arg.length > 1)
customView = arg[1];
// Keep Strings Neat By Using Variables (tm)
var elementid = "#" + id;
var template = templatePath + id;
if (customView != null)
template = templatePath + customView;
// Perform view rendering
$(elementid).html(new EJS({url: template}).render());
});
}
