creamer
Version:
A flatiron plugin for dynamic coffeecup templates
128 lines (121 loc) • 4.39 kB
text/coffeescript
cc = require 'coffeecup'
hardcode = require 'coffeecup-helpers'
fs = require 'fs'
wrench = require 'wrench'
exports.attach = (options={}) ->
self = this
registeredViews = {}
if options.views?
items = wrench.readdirSyncRecursive(options.views)
for view in items
if view.match /(.+)\.(js|coffee|coffee\.md)$/
fn = require options.views + '/' + view
name = view.split('.').shift()
registeredViews[name] = fn
if options.controllers?
items = wrench.readdirSyncRecursive(options.controllers)
for controller in items
if controller.match /(.+)\.(js|coffee|coffee\.md)$/
fn = require options.controllers + '/' + controller
@router.mount fn
if options.helpers?
items = wrench.readdirSyncRecursive(options.helpers)
for helper in items
match = helper.match /(.*)\.(js|coffee|coffee\.md)/
if match
fn = require options.helpers + '/' + helper
name = match[1].replace /[\. \/]+/g, '_'
valid = cc.compile(fn, {hardcode, locals: true})
hardcode[name] = fn if typeof fn is 'function'
@bind = (page, data) ->
html = ""
page = registeredViews[page] if typeof page is 'string'
data ?= {}
if @req?.session? then data.session = @req.session
if options.layout? and typeof page is 'function'
hardcode.content = page
html = cc.render(options.layout, data, { hardcode, locals: true })
else if typeof page is 'function'
html = cc.render(page, data, { hardcode, locals: true})
else
'<p>Not Found</p>'
if @res?
@res.html(html)
else
html
@registerHelper = (name, fn) ->
valid = cc.compile(fn, {hardcode, locals: true})
hardcode[name] = fn if typeof fn is 'function'
@registerView = (name, fn) ->
valid = cc.compile(fn, {hardcode, locals: true})
registeredViews[name] = fn
@router.attach ( -> @bind = self.bind ) if @router?.attach?
exports.init = (done) -> done()