-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathhandlebars.plugin.coffee
More file actions
75 lines (60 loc) · 2.07 KB
/
handlebars.plugin.coffee
File metadata and controls
75 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module.exports = (BasePlugin) ->
# Define Plugin
class HandlebarsPlugin extends BasePlugin
# Plugin name
name: 'handlebars'
# Handlebars
handlebars: null
# Constructor
constructor: ->
# Prepare
super
docpad = @docpad
config = @config
@handlebars = require('handlebars')
@precompileOpts = @config.precompileOpts || {}
# Generate Before
generateBefore: ->
# Add the template helper as a Handlebars helper
for own key,value of @docpad.getTemplateData()
if Object::toString.call(value) is '[object Function]'
@handlebars.registerHelper(key, value)
# Add helpers, if defined in docpad.cson
if @config.helpers
for own name,helper of @config.helpers
@handlebars.registerHelper(name, helper)
# Add partials, if defined in docpad.cson
if @config.partials
for own name,partial of @config.partials
@handlebars.registerPartial(name, partial)
# Render some content
render: (opts) ->
# Prepare
{inExtension,outExtension,templateData,content} = opts
handlebars = @handlebars
if inExtension in ['hb', 'hbs', 'handlebars']
if outExtension in ['js', 'inlinejs']
output = @handlePrecompileOpts(opts)
else
output = handlebars.compile(opts.content)(templateData)
opts.content = output
handlePrecompileOpts: (opts) ->
argv = @precompileOpts
argv.wrapper ?= "default"
argv.amdPath ?= ""
pre = post = "";
# slug for {src}/tpl/a/abc/test.js.handlebars is "tpl-a-abc-test"
templateName = opts.file.attributes.slug;
if (argv.wrapper is "amd")
pre += 'define([\'' + argv.amdPath + 'handlebars\'], function(Handlebars) {\n'
if (argv.wrapper is "default")
pre += '(function() {\n'
if (argv.wrapper in [ "default", "amd" ])
pre += ' var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n'
pre += 'templates[\'' + templateName + '\'] = template('
post += ');\n'
if (argv.wrapper is "amd")
post += '});'
if (argv.wrapper is "default")
post += '})();'
return pre + @handlebars.precompile(opts.content) + post