UNPKG

1.65 kBtext/coffeescriptView Raw
1path = require('path')
2Node = require('./node')
3
4# Directive node for HAML statements that change the meaning or do interact
5# uniquely with the HAML document.
6#
7# @example include a HAML document inside of another
8# +include 'path/to/template'[, context]
9#
10module.exports = class Directive extends Node
11
12 # Map of available directives to methods.
13 #
14 directives:
15
16 # Includes a HAML document inside of the current one. Context included
17 # template is defaulted to the context of this template but may be changed
18 # by passing a second argument.
19 #
20 # @example Include with default context
21 # +include 'path/to/template'
22 #
23 # @example Include with custom context
24 # +include 'path/to/template', @context
25 #
26 include: (expression) ->
27 try [[], name, context] = expression.match(/\s*['"](.*)['"](?:,\s*(.*))?\s*/)
28 catch e
29 throw new Error("Failed to parse the include directive from #{ expression }")
30
31 context = 'this' unless context
32 statement = switch @placement
33 when 'global' then "#{ @namespace }['#{ name }'].apply(#{ context })"
34 when 'amd' then "require('#{ name }').apply(#{ context })"
35 else
36 throw new Error("Include directive not available when placement is #{ @placement }")
37
38 @opener = @markInsertingCode statement, false
39
40 # Evaluate the Haml directive.
41 #
42 evaluate: ->
43 directives = Object.keys(@directives).join('|')
44 try [[], name, rest] = @expression.match(///\+(#{ directives })(.*)///)
45 catch e
46 throw new Error("Unable to recognize directive from #{ @expression }")
47
48 @directives[name].call this, rest