renderer.coffee 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. ### renderer.coffee ###
  2. fs = require 'fs'
  3. util = require 'util'
  4. async = require 'async'
  5. path = require 'path'
  6. mkdirp = require 'mkdirp'
  7. {Stream} = require 'stream'
  8. {ContentTree} = require './content'
  9. {pump, extend} = require './utils'
  10. if not setImmediate?
  11. setImmediate = process.nextTick
  12. renderView = (env, content, locals, contents, templates, callback) ->
  13. setImmediate ->
  14. # add env and contents to view locals
  15. _locals = {env, contents}
  16. extend _locals, locals
  17. # lookup view function if needed
  18. view = content.view
  19. if typeof view is 'string'
  20. name = view
  21. view = env.views[view]
  22. if not view?
  23. callback new Error "content '#{ content.filename }' specifies unknown view '#{ name }'"
  24. return
  25. # run view
  26. view.call content, env, _locals, contents, templates, (error, result) ->
  27. error.message = "#{ content.filename }: #{ error.message }" if error?
  28. callback error, result
  29. render = (env, outputDir, contents, templates, locals, callback) ->
  30. ### Render *contents* and *templates* using environment *env* to *outputDir*.
  31. The output directory will be created if it does not exist. ###
  32. env.logger.info "rendering tree:\n#{ ContentTree.inspect(contents, 1) }\n"
  33. env.logger.verbose "render output directory: #{ outputDir }"
  34. renderPlugin = (content, callback) ->
  35. ### render *content* plugin, calls *callback* with true if a file is written; otherwise false. ###
  36. renderView env, content, locals, contents, templates, (error, result) ->
  37. if error
  38. callback error
  39. else if result instanceof Stream or result instanceof Buffer
  40. destination = path.join outputDir, content.filename
  41. env.logger.verbose "writing content #{ content.url } to #{ destination }"
  42. mkdirp.sync path.dirname destination
  43. writeStream = fs.createWriteStream destination
  44. if result instanceof Stream
  45. pump result, writeStream, callback
  46. else
  47. writeStream.end result, callback
  48. else
  49. env.logger.verbose "skipping #{ content.url }"
  50. callback()
  51. items = ContentTree.flatten contents
  52. async.forEachLimit items, env.config._fileLimit, renderPlugin, callback
  53. ### Exports ###
  54. module.exports = {render, renderView}