Adding a New Template Engine

OscarGodson edited this page Nov 10, 2012 · 6 revisions

In this section, you will learn how to add a new templating engine to Punch. Code samples in this section is from the implementation of Handlebars engine for Punch.

Punch provides a BaseEngine, which we can inherit for our engine implementation.

	var BaseEngine = require("punch").TemplateEngines.Base;
	var util = require('util');

	function HandlebarsEngine(options){, options);

		this.extension = HandlebarsEngine.extension;
		this.renderFunction = HandlebarsEngine.renderFunction;

	util.inherits(HandlebarsEngine, BaseEngine);

The above code would look common for any engine implementation.

We need specify the file extension used by this template engine.

	HandlebarsEngine.extension = ".handlebars";

The meat of the template engine implementation is the defintion of the renderFunction. When rendering a page, Punch will call the renderFunction of the selected template engine. It will pass the following data as arguments:

  • layout (as a string)
  • Content object (content available for the page as name-value pairs)
  • Partials object (partials available for the page as name-value pairs)
  • Helpers object (helpers available for the page as name-value pairs)
	HandlebarsEngine.renderFunction = function(template, content, partials, helpers) {
		var renderedOutput = "";

		// implementation

		return renderedOutput;

Depending on the template engine you may have to decide how to handle the partials and helpers.

How to use a custom template engine

To use a custom template engine in a project, you have to define it as a plugin in project's configuration (config.json).

	"plugins": {
		"template_engine": "punch-engine-handlebars" 

Note that, plugin's path should be a valid Node.js module path.