Swig

A Node.js and Browser-based JavaScript Template Engine

Swig in the Browser

Most of Swig works in the browser in the same way that Swig works within node.js. The only exception to this is that Swig is unable to look up files by their path name, unless you directly tell Swig what each template's path name is before hand.

In short, Swig cannot resolve the directive {% extends "./myfile.html" %} and {% include "./myfile.html" %} without first having already been told about ./myfile.html.

The best way to work around this is to first pre-compile your templates using the Swig command-line interface.

  1. Compile each template into JavaScript files. Assign a method name to the output that will be globally available in your browser.

    $ swig compile myfile.html --method-name=myfile > myfile.js
  2. Include Swig and your myfile.js in your web page.

    <script src="swig.min.js"></script>
    <script src="myfile.js"></script>
    
  3. Pre-run the template to prime Swig's cache.

    swig.run(myfile, {}, '/myfile.html');
  4. Now, you are ready to render a template in-browser that can extend myfile.html

    var tpl = '{% extends "./myfile.html" %}{% block content %}{{ stuff }}{% endblock %}';
    var output = swig.render(tpl, { filename: '/tpl', locals: { stuff: 'awesome' }});
    document.querySelector('#foo').innerHTML = output;