eliseegw

Jade template packing for client-side usage with Express

Nov 6th, 2011
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. jade        = require 'jade'
  2. dive        = require 'diveSync'
  3.  
  4. compiledTemplates = ''
  5.  
  6. compileTemplates = (callback) ->
  7.   compiledTemplates = 'window.templates = {};'
  8.  
  9.   baseDirectory = __dirname + '/templates'
  10.  
  11.   dive baseDirectory, (err, file) ->
  12.     if err
  13.       throw err
  14.    
  15.     if path.extname(file) == '.jade'
  16.       name = file.replace(/\//g, '.')
  17.       name = name.substring( 0, name.length - '.jade'.length )
  18.       name = name.substring( baseDirectory.length + 1 )
  19.       compiledTemplates += 'templates.' + name + ' = ' + jade.compile( fs.readFileSync( file, 'utf-8' ), { client: true, compileDebug: false } ).toString() + ';'
  20.  
  21. # Compile the templates once on startup
  22. compileTemplates()
  23.  
  24. app.get '/javascripts/jade.js', (req, res) ->
  25.   # Serve the minified Jade runtime to the client
  26.   fs.readFile __dirname + '/node_modules/jade/runtime.min.js', 'utf-8', (err, data) ->
  27.     res.writeHead 200, 'Content-Type': 'text/javascript'
  28.     res.end data
  29.  
  30. app.get '/javascripts/templates.js', (req, res) ->
  31.   # If we aren't in production, recompile the templates to ensure they are up to date
  32.   if !process.env.PRODUCTION
  33.     compileTemplates()
  34.  
  35.   res.writeHead 200, 'Content-Type': 'text/javascript'
  36.   res.end compiledTemplates
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment