malgorithms / toffee

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

Question: API render #29

Closed hhsnopek closed 10 years ago

hhsnopek commented 10 years ago

With the API does render also take strings?

malgorithms commented 10 years ago

there's toffee.strRender, which takes a template string, a value dictionary, and a callback function.

hhsnopek commented 10 years ago

Figured it out, beautiful! Thank you :+1:

malgorithms commented 10 years ago

awesome. I was about to reply.

Here's a an example in CoffeeScript:

toffee = require 'toffee'

template = '''
<h1>Hi, #{name}</h1>

<p>Check out this math!</p>
{#
   for x in [0...10] {:
      #{x}+1 equals #{x+1}!
   :}
#}

'''

toffee.strRender template, {name: 'HHSnopek'}, (err, res) ->
  console.log res

If you're going to use the same template repeatedly, you can compile it separately, which will save you from recompiling each time. This has the added advantage that it doesn't use the callback technique (as it was designed for Express 1.0). I dunno where it is in your call stack but you might like it more.

template = '''
<h1>Hi, #{name}</h1>

<p>Check out this math!</p>
{#
   for x in [0...10] {:
      #{x}+1 equals #{x+1}!
   :}
#}

'''
renderer = toffee.compile template
console.log renderer({name: 'HHSnopek'})

It has the disadvantage that you'll have to try/catch.

hhsnopek commented 10 years ago

toffee.compile template {name: 'hhsnopek' } is valid?

hhsnopek commented 10 years ago

if it is, could you update your API docs? I'm working with nodejs btw

malgorithms commented 10 years ago

no, template, is just a string, not a function. coffeescript parses the other way. but yeah, in javascript, you could do:

var whatever = toffee.compile(template)({name:"HHS"});
malgorithms commented 10 years ago

also, check out the fourth item on this page in the wiki:

https://github.com/malgorithms/toffee/wiki/NodeJS-Usage

I forgot about that interface, and it might be ideal since it catches the errors for you. By the way, all these slightly different interfaces exist so that Toffee can be dropped into different publishing platforms like consolidated.js, express 1, 2, etc.

hhsnopek commented 10 years ago

I'm using coffeescript :smile: Thank you!

malgorithms commented 10 years ago

I was vague above about the parsing. This:

toffee.compile template {name: 'hhsnopek' }

parses function calls right to left in coffee. So it would call template({name:'h'}), and then toffee.compile on the output of that, which doesn't make sense, since template is a string not a function.

I think you'd want to use parens in this case, even in coffee:

toffee.compile(template)({name: 'hhsnopek' })