Writing a Custom Content Handler

laktek edited this page Mar 31, 2013 · 6 revisions

By writing a custom content handler, you can fetch data for your site from any source that can output JSON. This could be a relational database like Postgre, REST API to a web service, document store like CouchDB or a backend service like Firebase. By writing custom content handler you can get Punch to power any kind of a site you want.

A custom content handler should implement the following functions:

    module.exports = {
          setup: function(config) {
            // read the config.json
            // and extract necessary properties

      isSection: function(request_path) {
            // return if the given path is a section

      getSections: function(callback) {
            // return all sections available under contents

      negotiateContent: function(request_path, content_type, options, callback) {
            // invoke the callback with the content for the given request_path and content type
            var self = this;
            var error = null;
            var content = {};
            var response_options = {};
            var last_modified = new Date();

            return callback(error, content, response_options, last_modified);

      getContentPaths: function(request_path, callback) {
           // invoke the callback with all content paths stems from the given request_path


In Punch, directory paths such as /blog, /archive/code are treated as sections and an index file in the directory will be rendered when such paths are called. Depending on the structure of your site, you can specify which paths should be sections.

Punch will call the negotiateContent function, to fetch contents for a given path. Following arguments will be passed with the call: request_path, content_type(file_extension), request_options and a callback.

After fetching content, you must invoke the callback, as shown in the example.

Note: Response Options defines a list of response_options you can set.

For sample implementations of custom content parsers, you may take a look at the custom content handler used in FavTweets example and Simple Markdown Content Handler.

How to use a custom content handler

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

    "plugins": {
        "content_handler": "custom_content_handler" 

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