-
Notifications
You must be signed in to change notification settings - Fork 10
NodeJs Usage
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
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.
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.
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
.
You can access the default engine directly with toffee.render
toffee = require 'toffee'
toffee.render 'foo.toffee', {title: "bar"}, (err, res) -> console.log res
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] = v.run {name: "Chris"}
If you want, you can pass view.run a partial
function, so your views can include other views.
[err, res] = v.run {
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
.
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'}