Skip to content
This repository has been archived by the owner on Nov 27, 2018. It is now read-only.

Writing Custom Helpers

Lakshan Perera edited this page Sep 13, 2012 · 6 revisions

Helpers provide a simple, but powerful way to augment a page's output at the time of rendering. This can be useful to add context specific data into the page (such as current time or current path) or to enhance existing data.

Punch ships with a minimal set of default helpers. But you can easily create your own helpers as per your requirements.

AssetBundleHelper, which is available in Punch as a default helper and SiteHelpers in FavTweets are good case studies to understand the capabilities of helpers.

Setup

Punch will load (require) all available helpers when you start the server or calls punch generate. After loading a helper, Punch will call the setup function of the helper. It will pass configuration options defined for the site as an object.

	setup: function(config) {
		// initialize and store any required configuration settings
	}

Lifecycle

When serving a request, Punch will call the get function in each available helper with the following arguments: request path, file extension, request options and a callback.

	get: function(basepath, file_extension, options, callback){
		var error = null;
		var tag_helpers = {};
		var block_helpers = {};
		var response_options = {};
		var last_modified = new Date();

		return callback(error, { "tag": tag_helpers, "block": block_helpers }, response_options, last_modified);
	}

Tag & Block Helpers

The get function, should invoke the callback with the arguments as specified in the example. If there's an error Punch will ignore any other arguments passed. Tag and block helpers defines special tags that you can use in the layouts. Primary difference between a tag and block helper is, tag helper cannot accept arguments (eg. {{timestamp}}), while block helper can accept arguments (eg. {{#upcase}}hello{{/upcase}}). In Mustache, block helpers are treated as lambda sections.

Response Options

Apart from the tag and block helpers, you can pass another object called response_options. You can use response options to modify the response headers, status, etc.

The following code is from the SiteHelper of [FavTweets] example. See how it sets a cookie using response options.

	get: function(basepath, file_extension, request_options, callback) {
		var self = this;
		var response_options = { "header": {} };

		if (basepath === "/index") {
			response_options.header["Set-Cookie"] = "bg=" + getRandomInt(0, 1);
			return callback(null, { "index": true }, {}, response_options); 
		} else {
			return callback(null, { "index": false }, {}, response_options); 
		}
	}

Last Modified

You can optionally pass a last modified date for a helper call. This is useful for invalidating the cache and force rendering.