-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathdirective.coffee
More file actions
79 lines (67 loc) · 2.78 KB
/
Copy pathdirective.coffee
File metadata and controls
79 lines (67 loc) · 2.78 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
76
77
78
79
path = require('path')
Node = require('./node')
unless process.browser
fs = require('fs')
CoffeeScript = require 'coffee-script'
# Directive node for HAML statements that change the meaning or do interact
# uniquely with the HAML document.
#
# @example include a HAML document inside of another
# +include 'path/to/template'[, context]
#
module.exports = class Directive extends Node
# Map of available directives to methods.
#
directives:
# Includes a HAML document inside of the current one. Context included
# template is defaulted to the context of this template but may be changed
# by passing a second argument.
#
# @example Include with default context
# +include 'path/to/template'
#
# @example Include with custom context
# +include 'path/to/template', @context
#
include: (expression) ->
try [[], name, context] = expression.match(/\s*['"](.*?)['"](?:,\s*(.*))?\s*/)
catch e
throw new Error("Failed to parse the include directive from #{ expression }")
context = 'this' unless context
statement = switch @placement
when 'global' then "#{ @namespace }['#{ name }'](#{ context })"
when 'amd' then "require('#{ name }')(#{ context })"
when 'standalone'
if browser?.process
throw new Error("Include directive not available in the Browser when placement is standalone.")
else
# A standalone template cannot depend on another template so
# we need to compile the referenced template and attach it as a
# precompiled (standalone) template here.
templatePath = path.join(
@options.compilerOptions.pwd,
"#{ name }.#{ @options.compilerOptions.extension }"
)
# Read the source.
try
source = fs.readFileSync(templatePath).toString()
catch error
console.error " Error opening file: %s", error
console.error error
# Compile and build the source function.
Compiler = require '../haml-coffee'
compiler = new Compiler(@options.compilerOptions)
compiler.parse source
code = CoffeeScript.compile(compiler.precompile(), bare: true)
statement = "`(function(){#{code}}).apply(#{context})`"
else
throw new Error("Include directive not available when placement is #{ @placement }")
@opener = @markInsertingCode statement, false
# Evaluate the Haml directive.
#
evaluate: ->
directives = Object.keys(@directives).join('|')
try [[], name, rest] = @expression.match(///\+(#{ directives })(.*)///)
catch e
throw new Error("Unable to recognize directive from #{ @expression }")
@directives[name].call this, rest