vol4ok / hogan-express

Mustache template engine for express 3.x. Support partials and layout
MIT License
138 stars 31 forks source link

READY: add better lambda/filter support #16

Closed EddieCanales closed 11 years ago

EddieCanales commented 11 years ago

Currently, in order to implement filters/lambdas you have to know and do a lot. You have to:

  1. include hogan.js in your app
  2. know the strange "lambda factory"-ish style of using a function that returns a function
  3. realize that what you get as "text" in the function call is the pre-rendered/compiled template snippet
  4. know the hogan.js API for compiling and rendering the template snippet
  5. pass around variables/context (especially when trying to operate on objects within an array loop)

This pull request encapsulates all of that for you so you can simply define your lambdas as functions that should be run on the processed template snippet. For example:

app.get '/', (req,res)->

  res.locals = myDefaultLabel: "oops" # here to show a little of how scoping works

  res.render 'template',
    message: 'This is a message. HERE.'
    mylist: [{label: "one", num: 1},{label: "two", num: 2},{num: 3}]

    lambdas:
     lowercase: (text) ->
       return text.toLowerCase()
     reverseString: (text) ->
       return text.split("").reverse().join("")

template:

<p>Lowercase <strong>{{message}}</strong>: {{#lambdas.lowercase}}{{message}}{{/lambdas.lowercase}}</p>
<ul>
  {{#mylist}}
  <li>{{num}}: {{label}} is {{#reverseString}}{{label}}{{#reverseString}} in reverse.</li>
  {{/mylist}}
</ul>

rendered html:

<p>Lowercase <strong>This is a message. HERE.</strong>: this is a message. here.</p>
<ul>
  <li>1: one is eno in reverse.</li>
  <li>2: two is owt in reverse.</li>
  <li>3: oops is spoo in reverse.</li>
</ul>

You can see this in action in the example app. I also wrote some tests (mocha+supertest) that exercise this new feature within the app. README was also updated to reflect the new feature.

vol4ok commented 11 years ago

I merged the pull request and updated version to 0.5.0-rc. I'll review new feature soon and if everything ok I'll publish it to npm. Thank you.

vol4ok commented 11 years ago

OK, published to npm