Skip to content

Instantly share code, notes, and snippets.

@klclee
Created May 24, 2013 22:48
Show Gist options
  • Save klclee/5647014 to your computer and use it in GitHub Desktop.
Save klclee/5647014 to your computer and use it in GitHub Desktop.
a straight forward plain HTML template engine with connect assets support
fs = require 'fs'
path = require 'path'
Instance = ->
# cache for templates, express 3.x doesn't do this for us
@cache = {};
@__express = middleware.bind(@)
return
middleware = (filename, options, cb) ->
cache = @cache
# grab extension from filename
# if we need a layout, we will look for one matching out extension
extension = path.extname filename
# render the original file
render_file = (locals, cb) ->
template = cache[filename]
return cb(null, template) if template?
fs.readFile filename, 'utf8', (err, str) ->
return cb(err) if err?
locals = options
final_str = js_replace(str)
final_str = css_replace(final_str)
cache[filename] = final_str if options.cache
cb(null, final_str)
render_file(options, cb)
js_replace= (str) ->
sub(str, /{{{js\s(.*)}}}/g, 'js')
css_replace= (str) ->
sub(str, /{{{css\s(.*)}}}/g, 'css')
sub = (str, patt, type) ->
final_str = str
for matched in str.match(patt)
final_str = final_str.replace(matched, eval(type) matched.split("{{{#{type} ")[1].split('}}}')[0].trim())
final_str
module.exports = new Instance()
module.exports.create = ->
new Instance()
@klclee
Copy link
Author

klclee commented May 24, 2013

to use it:

assets = require 'connect-assets'
raw = require './raw'

app.use assets()
app.set 'view engine', 'raw'
app.engine 'html', raw.__express

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment