Skip to content

NodeJs Usage

Chris Coyne edited this page Jul 1, 2013 · 10 revisions

In any NodeJs program, you can use Toffee to publish any template and vars into a string.


If you haven't yet, install the toffee module:

> npm install -g toffee

Usage - You Have Lots of Options

0. Using it with Express

For convenience, just read Using Toffee in Express. You can return to this page if you want to customize Toffee, but setup with Express is designed to be easy.

1. Creating an engine and using it.

An engine is a layer on top of Toffee's publishing that takes care of monitoring files, caching, pretty-printing errors, and managing some global preferences. It's what you typically want in a website project. (Note if you're using Express you can jump to Using Toffee in Express.)

Here's an example of creating an engine and using it to publish a file:

toffee = require 'toffee'
engine = new toffee.engine()

engine.render 'some-file-1.toffee', { var1: "hello", var2: "world" }, (err, res) ->
   console.log res

engine.render 'some-file-2.toffee', {}, (err, res) -> console.log res

Important: The engine is responsible for managing preferences and caching your templates, so don't create a new engine every time you render.

Engine options:

You have a bunch of options with your engine (how to handle errors, verbosity, all kinds of stuff). Follow the "Advanced Options" link at the bottom to read more.

But here's an example:

engine = new toffee.engine {
   prettyPrintErrors: false # defaults to true 
   verbose: true            # defaults to false

When prettyPrintErrors is true (the default), template compiling and runtime errors are packaged up into pretty html and put into res instead of err.

2. Skipping the engine creation, and using the default one

You can access the default engine directly with toffee.render

toffee = require 'toffee'
toffee.render 'foo.toffee', {title: "bar"}, (err, res) -> console.log res

3. Creating a 'view' which exposes a run function.

If an engine is more than you want, you can simply compile templates yourself. A template in Toffee is called a 'view' and it's easy to build and use:

v = new toffee.view '''

  Dear #{name},
     Here be some odd numbers: 
       #{(x for x in [1...20] by 2).join ', '}


[err, res] = {name: "Chris"}

If you want, you can pass a partial function, so your views can include other views.

[err, res] = {
   name:    "Chris"
   partial: (filename, vars) -> "Do something with #{filename} and #{vars} that returns a string"

Of course, you can pass whatever functions you want, not just partial.

4. The simplest of all: compileStr

A convenience function, compileStr wraps around creating a view and returning its run function. Here's the simplest way to compile a string template in Toffee.

fn = toffee.compileStr 'Hi there, #{name}'
[err, res] = fn {name: 'Spiderman'}

See Also

Something went wrong with that request. Please try again.