UNPKG

2.91 kBtext/coffeescriptView Raw
1fs = require 'fs'
2
3Compiler = require './haml-coffee'
4
5if process.browser
6 CoffeeScript = window.CoffeeScript
7else
8 CoffeeScript = require 'coffee-script'
9
10# Express 3 template Cache
11__expressCache = {}
12
13# Facade to Haml Coffee for easy template function
14# compiling and JST template rendering.
15#
16module.exports =
17
18 # Compile the Haml Coffee template into
19 # a JavaScript function.
20 #
21 # @see {Compiler} for a complete list of the supported
22 # compiler options.
23 #
24 # @param [String] source the Haml Coffee source
25 # @param [Object] options the compiler options
26 # @return [Function] the template
27 #
28 compile: (source, options = {}) ->
29 compiler = new Compiler(options)
30 compiler.parse source
31
32 template = new Function CoffeeScript.compile(compiler.precompile(), bare: true)
33
34 (params) -> template.call params
35
36 # Creates the JavaScript Template.
37 #
38 # @see {Compiler} for a complete list of the supported
39 # compiler options.
40 #
41 # @param [String] source the Haml Coffee source
42 # @param [String] name the template name
43 # @param [String] namespace the template namespace
44 # @param [Object] options the compiler options
45 # @return [String] the template source code
46 #
47 template: (source, name, namespace, options = {}) ->
48 compiler = new Compiler(options)
49 compiler.parse source
50
51 CoffeeScript.compile compiler.render(name, namespace)
52
53 # Express 3 templating interface with template function cache.
54 # When the template function cache is enabled by setting `cache`
55 # in the options to true, the compiled JavaScript template function
56 # is cached, which improves speed a lot, since it it only parses,
57 # generates and compiles to template once.
58 #
59 # @overload __express(filename, callback)
60 # Compiles and renders a template
61 # @param [String] filename the template file path
62 # @param [Function] the callback
63 #
64 # @overload __express(filename, options, callback)
65 # Compiles and renders a template
66 # @param [String] filename the template file path
67 # @param [Object] options the compiler options and template locals
68 # @option options [Boolean] cache whether to cache the template or not
69 # @param [Function] the callback
70 #
71 __express: (filename, options, callback) ->
72 # Parameter shift
73 if !!(options and options.constructor and options.call and options.apply)
74 callback = options
75 options = {}
76
77 try
78 if options.cache and __expressCache[filename]
79 callback null, __expressCache[filename](options)
80
81 else
82 options.filename = filename
83 source = fs.readFileSync(filename, 'utf8')
84
85 if options.cache
86 __expressCache[filename] = module.exports.compile(source, options)
87 callback null, __expressCache[filename](options)
88
89 else
90 callback null, module.exports.compile(source, options)(options)
91
92 catch err
93 callback err