Swig

A Node.js and Browser-based JavaScript Template Engine

Template Loaders

Built-In Loaders

swig.loaders.fs(basepath, encoding)

Source: lib/loaders/filesystem.js

Loads templates from the file system.

Arguments

Name Type Optional Default Description
basepath string โœ” ''

Path to the templates as string. Assigning this value allows you to use semi-absolute paths to templates instead of relative paths.

encoding string โœ” 'utf8'

Template encoding

swig.setDefaults({ loader: swig.loaders.fs() });
// Load Templates from a specific directory (does not require using relative paths in your templates)
swig.setDefaults({ loader: swig.loaders.fs(__dirname + '/templates' )});

swig.loaders.memory(mapping, basepath)

Source: lib/loaders/memory.js

Loads templates from a provided object mapping.

Arguments

Name Type Optional Default Description
mapping object

Hash object with template paths as keys and template sources as values.

basepath string โœ”

Path to the templates as string. Assigning this value allows you to use semi-absolute paths to templates instead of relative paths.

var templates = {
  "layout": "{% block content %}{% endblock %}",
  "home.html": "{% extends 'layout.html' %}{% block content %}...{% endblock %}"
};
swig.setDefaults({ loader: swig.loaders.memory(templates) });

Custom Loaders

Swig is able to accept custom template loaders written by you, so that your templates can come from your favorite storage medium without needing to be part of the core library.

A template loader consists of two methods: resolve and load. Each method is used internally by Swig to find and load the source of the template before attempting to parse and compile it.

resolve(to, from)

Resolves to to an absolute path or unique identifier. This is used for building correct, normalized, and absolute paths to a given template.

Arguments

Name Type Description
to string

Non-absolute identifier or pathname to a file.

from string

If given, should attempt to find the to path in relation to this given, known path.

load(identifier, cb)

Loads a single template. Given a unique identifier found by the resolve method this should return the given template.

Arguments

Name Type Description
identifier string

Unique identifier of a template (possibly an absolute path).

cb function

Asynchronous callback function. If not provided, this method should run synchronously.

Examples

// A theoretical memcached loader
var path = require('path'),
  Memcached = require('memcached');
function memcachedLoader(locations, options) {
  var memcached = new Memcached(locations, options);
  return {
    resolve: function (to, from) {
      return path.resolve(from, to);
    },
    load: function (identifier, cb) {
      memcached.get(identifier, function (err, data) {
        // if (!data) { load from filesystem; }
        cb(err, data);
      });
    }
  };
};
// Tell swig about the loader:
swig.setDefaults({ loader: memcachedLoader(['192.168.0.2']) });