-
Notifications
You must be signed in to change notification settings - Fork 1
Precompiler
wvl edited this page Sep 11, 2012
·
2 revisions
ncc templates are templates as code, heavily inspired by coffeekup (or it's maintained fork: coffeecup).
h1 '@pageTitle'
$if '@loggedIn', (->
h2 'Hello '+ctx('name')
), ->
h2 'Join Now'
ul ->
$each '@benefits', ->
li '@name'
The precompiler translate valid coffeescript code into an nct template, which is then compiled into a javscript function. This creates small, compact and fast functions.
ncc templates follow fairly simple rules:
- html tags are available as local functions
h1 'Hello'
=> <h1>Hello</h1>
- Nest tags by passing a function to the tag
div ->
span 'Hello'
=> <div><span>Hello</span></div>
- Attach attributes to dom elements by passing an object to the function:
div {style: 'display: none;'}, ''
=> <div style="display: none;"></div>
With nested objects:
div {data: {key: 'value'}}, ''
=> <div data-key="value"></div>
- Attach ids and classes to dom elements by using the shortcut form:
div '#myid.one.two', ''
=> <div id="id" class="one two"></div>
- Context lookups use the ctx function:
ctx('msg')
=> { msg }
or:
div -> ctx('name')
=> <div>{ name }</div>
- Conditionals and loops are prefixed with $:
$if ctx('user'), ->
div -> "Hello: "+ctx('user.name')
$each ctx('people') ->
li -> ctx('name')
=> {# people}<li>{ name }</li>{/#}
- Inside conditionals, loops, and tag functions, context lookups can be simplified by prefixing a string with '@':
$if '@user', ->
div '@user.name'
Because these templates are just code, you can create macros, and compose them together as needed:
# forms.coffee
c = require('nct').coffee
exports.field = (name) ->
c.div '.control-group', ->
c.label '.control-label', for: name, name
c.div '.controls', ->
c.input '.span4', {name, type: 'text'}
# signup.coffee
forms = require('./forms')
form ->
forms.field('username')
forms.field('email')