Skip to content

billykong/simple-templating-engine

Repository files navigation

Build Status Coverage Status npm version Run on Repl.it

Simple Template Engine

Usage

var templeteEngine = require('./simple_templating_engine.js');
var template = "Hello, <% change_me %>";
var handlerWorld = function(key) { return { '<% change_me %>': 'World' } };

templeteEngine.populate(template, handlerWorld).then(populated => {
    console.log(populated); // "Hello, World"
});

var handlerAsyncWorld = function(key) { return { '<% change_me %>': 'Async World' } };
(async function() {
  let populated = await templeteEngine.populate(template, handlerAsyncWorld);
  console.log(populated); // Hello, Async World
})();

It also work with JSON template:

var templateJSON = `{ "root": <% change_me %> }`;
var handlerJSON = function(key) { 
  return { 
    '<% change_me %>': { 
      'key1': 'value1',
      'key2': 'value2'
    } 
  } 
};

templeteEngine.populate(templateJSON, handlerJSON).then(populated => {
    console.log(JSON.parse(populated)); 
    // { "root": {"key1":"value1","key2":"value2"} }
});

The handler can be an async function when we need to call remote APIs to get data:

var handlerJSON = async function(key) { 
  return await {
    '<% change_me %>': { 
      'key1': 'value1',
      'key2': 'value2'
    } 
  } 
};
templeteEngine.populate(templateJSON, handlerJSON).then(populated => {
    console.log(populated); 
});

You can also use another matcher pattern other than <% ... %>:

var template = "Hello, {_ change_me _}";
var options = { matcher: /"{_([^%>]+)?_}"/g}
var handler = function(key) { return { '{_ change_me _}': 'World' } };

templeteEngine.populate(template, handler, options).then(populated => {
    console.log(populated); // "Hello, World"
});