fevangelou
2/24/2012 - 2:59 PM

Include tag for underscore template

Include tag for underscore template

// based on http://emptysquare.net/blog/adding-an-include-tag-to-underscore-js-templates/

    // include tag for underscore templates
    // <% include template-id %>
    var _underscore_template = _.template;
    _.template = function(str, data) {
        // match "<% include template-id %>"
        return _underscore_template(
            str.replace(
                /<%\s*include\s*(.*?)\s*%>/g,
                function(match, templateId) {
                    var el = $('#' + templateId);
                    return el ? el.html() : '';
                }
            ),
            data
        );
    };


/* templates 

<script type="text/template" id="foo">
   foo
</script>

<script type="text/template" id="bar">
    <% include foo %>
    bar     
</script>

*/