malgorithms / toffee

a NodeJS and browser templating language based on coffeescript, with the slickest syntax ever
MIT License
174 stars 10 forks source link

API for compiling one string template? #20

Open pwnall opened 11 years ago

pwnall commented 11 years ago

Is there an API that I can use if I want to compile a single Toffee template string into a function that I can call with the context?

This would be useful for integrating Toffee into a system that already has its own caching and partials.

I've been playing with toffee.view and its run, and I'm wondering if that's a good path to follow.

malgorithms commented 11 years ago

Hey @pwnall -- make sure you have toffee 0.1.3 and any of these examples should work:

toffee = require 'toffee'

# ----------------------------------
# An example, using a view
# ----------------------------------

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"}

console.log res

Note that the view can take an optional second parameter with your autoescape, etc., settings, as mentioned in the documentation. It can also take a "fileName" var which helps with debugging.

Alternatively, for convenience, you can create the view and return its run function in one swoop, with the convenience function compileStr:

# ------------------------------------------------
# An example using the convenience function compileStr
# ------------------------------------------------

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

If you want to use your own partial function, you can.

# ------------------------------------------------
# An example, using your own partial function + a view
# ------------------------------------------------

v = new toffee.view 'Hi there, #{name}. Check out #{partial "foo.toffee", {age:212} }'

[err, res] = v.run {
  name: "Batman"
  partial: (fname, vars) -> "\n\nTODO: implement partials so I can print #{fname} / #{vars}"
}

And again, you can use the compileStr convenience function if you prefer:

# ------------------------------------------------
# An example, using your own partial function + compileStr
# ------------------------------------------------

fn          = toffee.compileStr 'Hi there, #{name}. Check out #{partial "foo.toffee", {age:22} }'

[err, res]  = fn {
  name: 'George Bluth'
  partial: (fname, vars) -> "\n\nTODO: implement partials so I can print #{fname} / #{vars}"
}

Let me know if this answers your question...

-Chris