Bec d'état - Rebecca Scott

Blog | Links | Archive
About | Resume | Advisor profile | Projects | Contact

~/Cliche – an extremely simple view template engine for jQuery

21 Dec 2009

I’ve written a very simple plugin for jQuery that takes a template and a model and returns a view of the model. The plugin itself is pretty straightforward:

    $.fn.cliche = function(model){
        var template = $(this).html();
        // pipes in a href like <a href="|... get converted to %7C, convert it back:
        template = template.replace(/%7C/g, '|');
        template = template.replace(/\|.*?\|/g, function(f) {
            var val = model;
            var fieldParts = f.replace(/\|/g, '').split('.');
            for (var i = 0; i < fieldParts.length; i ++) {
                val = val[fieldParts[i]];
            return val;
        return template;

It is used by setting up a template (putting it into a script type="text/html” block is convenient and hides it from display) and calling cliche(model) on the jQuery object:

<div id="output">
<script type="text/html" id="testTemplate">
    <li id="item|id|"><a href="viewItem?id=|id|">|name|</a></li>
<script type="text/javascript">
    $('#output ul').append(
            id: 1, name: 'Lorem'
Cliche is licensed under a Creative Commons Attribution 2.5 Australia license. Check it out at