External template in Underscore

Here is a simple solution:

var rendered_html = render('mytemplate', {});

function render(tmpl_name, tmpl_data) {
    if ( !render.tmpl_cache ) { 
        render.tmpl_cache = {};
    }

    if ( ! render.tmpl_cache[tmpl_name] ) {
        var tmpl_dir="/static/templates";
        var tmpl_url = tmpl_dir + "https://stackoverflow.com/" + tmpl_name + '.html';

        var tmpl_string;
        $.ajax({
            url: tmpl_url,
            method: 'GET',
            dataType: 'html', //** Must add 
            async: false,
            success: function(data) {
                tmpl_string = data;
            }
        });

        render.tmpl_cache[tmpl_name] = _.template(tmpl_string);
    }

    return render.tmpl_cache[tmpl_name](tmpl_data);
}

Using “async: false” here is not a bad way because in any case you must wait until template will be loaded.

So, “render” function

  1. allows you to store each template in separate html file in static
    dir
  2. is very lightweight
  3. compiles and caches templates
  4. abstracts template loading logic. For example, in future you can use preloaded and precompiled templates.
  5. is easy to use

[I am editing the answer instead of leaving a comment because I believe this to be important.]

if templates are not showing up in native app, and you see HIERARCHY_REQUEST_ERROR: DOM Exception 3, look at answer by Dave Robinson to What exactly can cause an “HIERARCHY_REQUEST_ERR: DOM Exception 3”-Error?.

Basically, you must add

dataType: 'html'

to the $.ajax request.

Leave a Comment