Handlebars template engine support

Karpich Dmitry edited this page Jul 5, 2015 · 3 revisions

Good news, we are support custom file processor and I introduce it with Handlebars example.

Full worked on-line example see at demo page - handlebars demo.

Some preparations

As first - while custom processors is add-on for clinch - you are handle all additional modules by yourself.

For Handlebars its means you should to install handlebars as part of your project:

npm install handlebars --save

As second - usually template engine have some kind of runtime lib pack to use it in browser with pre-compiled templates.

For Handlebars its means you should include at your browser page handlebars.runtime.js file. Its placed in dist directory of Handlebars.

Main part

Example of template (template.handlebars)

<div class="message"><p>Hello {{ name }}!!!</p></div>

Example of module, which use template (handelarsed.coffee)

module.exports = class HandlebarsPowered
  This method render results with Handlebars template and given data
  renderData : (data) ->
    template_fn = require './template'
    template = Handlebars.template template_fn
    res = template data

And builder part for clinch it in

Clinch     = require 'clinch'
Handlebars = require 'handlebars'

clinch_obj = new Clinch

package_config = 
  package_name : 'my_package'
  bundle : 
    HandlebarsPowered : "#{__dirname}/handelarsed"

# add .handlebars processor
clinch_obj.registerProcessor '.handlebars', (data, filename, cb) ->
  content = Handlebars.precompile data
  cb null, "module.exports = #{content}"

packer.buldPackage pack_config, (err, data) ->
  # process data - save it to file or send it to client as express answer

Add result to browser page (and dont forget for handlebars.runtime.js) and use our method:

{HandlebarsPowered} = my_package

handlebars_obj = new HandlebarsPowered()
res = handlebars_obj.renderData name : 'Bender'

And now in res should be

<div class="message"><p>Hello Bender!!!</p></div>