Skip to content
Cameron J Roe edited this page Jan 20, 2016 · 9 revisions

When you compile a template, you can pass the customTags option to set your custom tag parser.

Example:

var render = tinyliquid.compile('{% say_hello name %}', {
  customTags: {
    say_hello: function (context, name, body) {
      // the first argument is the current parser context, different with tinyliquid.newContext()
      // the second argument is the current tag name, in this example is "say_hello"
      // the third argument is the tag content, in this example is "name"
      // use context.astStack.push(ast) to add the results to the AST tree
      // so we can convert the custom tag to the base tag template => Hello, {{name}}!
      // and use tinyliquid.parse() to get the results
      var ast = tinyliquid.parse('Hello, {{' + body.trim() + '}}!');
      context.astStack.push(ast);
    }
  }
});

var context = tinyliquid.newContext();
context.setLocals('name', 'world');
render(context, function (err) {
  if (err) console.error(err);
  console.log(context.getBuffer());  // will output "Hello, world!"
});

This is the other example below:

var tinyliquid = require('tinyliquid');

// custom tags parser
var customTags = {};
// Example:
// {% paginate posts by 30 %}
//   {% for post in posts %}{{post.title}}{% endfor %}
// {% endpaginate %}
customTags.paginate = function (context, name, body) {
  // Example:     {% paginate posts by 30 %}
  // Convert to:  {% assign posts = "posts" | query_list: 30, query_page %}
  var bs = body.split(/\s+/);
  var n = bs[0];
  var p = bs[2];
  var tpl = '{% assign ' + n + ' = "' + n + '" | query_list: ' + p + ', query_page %}';
  context.astStack.push(tinyliquid.parse(tpl));
};
customTags.endpaginate = function (context, name, body) {
  // Do nothing.
};

var tpl = '{% paginate data by 30 %}' +
            '{% for item in data %}{{item}}{% unless forloop.last %},{% endunless %}{% endfor %}' +
          '{% endpaginate %}';
var render = tinyliquid.compile(tpl, {customTags: customTags});
var context = tinyliquid.newContext();
// we need a locals variable "query_page" and a filter "query_list"
// "query_page" is the current page number
// "query_data_list" use to get the data list
context.setLocals('query_page', 1);
context.setAsyncFilter('query_list', function (name, size, page, callback) {
  // the first argument is the data list name
  // the second argument is the page size
  // the third argument is the page number
  // do something to query the data...
  if (name === 'data') {
    setTimeout(function () {
      var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      callback(null, data);
    }, 100);
  } else {
    callback(null, []);
  }
});
// now rendering
render(context, function (err) {
  if (err) console.error(err);
  console.log(context.getBuffer());  // will output "1,2,3,4,5,6,7,8,9,10"
});

>

Clone this wiki locally