Class: Handlebar::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/handlebar/template.rb

Defined Under Namespace

Classes: ArgumentError, MissingVariable, ParseError, RecursionError, TemplateHash, VariableTracker

Constant Summary collapse

TOKEN_REGEXP =

Constants ============================================================

/((?:[^\{]|\{[^\{]|\{\{\{)+)|\{\{\s*([\&\%\$\.\:\?\*\/\=])?([^\}]*)\}\}/.freeze
TOKEN_TRIGGER =
/\{\{/.freeze

Instance Method Summary collapse

Constructor Details

#initialize(content, options = nil) ⇒ Template

Instance Methods =====================================================



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/handlebar/template.rb', line 30

def initialize(content, options = nil)
  if (options)
    if (source = options[:escape])
      case (source.to_sym)
      when :html, :html_escape
        @escape_method = :html_escape
      when :text, nil
        # Default, ignored
      else
        raise ArgumentError, "Unknown escape source #{source}"
      end
    end
  end
  
  @content =
    case (content)
    when IO
      content.read
    else
      content.to_s
    end
end

Instance Method Details

#compile(options) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/handlebar/template.rb', line 124

def compile(options)
  escape_method = options[:escape_method]
  sections = options[:sections]
  templates = options[:templates]
  variables = options[:variables]
  source = options[:source]

  stack = [ [ :base, nil, VariableTracker.new ] ]
  stack_variables = nil
  
  @content.scan(TOKEN_REGEXP).each do |text, tag_type, tag|
    if (text)
      text = text.sub(/\{(\{\{+)/, '\1').sub(/\}(\}\}+)/, '\1')
      
      source and source << "r<<#{text.inspect};"
    else
      tag = tag.strip
      tag = tag.empty? ? nil : tag.to_sym
      
      case (tag_type)
      when ?&
        # HTML escaped
        index = stack[-1][2][tag.inspect]

        source and source << "v&&r<<h.html_escape(v[#{tag.inspect}].to_s);"
        
        variables and variables[tag] = true

      when ?%
        # URI escaped
        index = stack[-1][2][tag.inspect]

        source and source << "v&&r<<h.uri_escape(v.is_a?(Array)?v[#{index}]:v[#{tag.inspect}]);"

        variables and variables[tag] = true
      when ?$
        # JavaScript escaped
        index = stack[-1][2][tag.inspect]

        source and source << "v&&r<<h.js_escape(v.is_a?(Array)?v[#{index}]:v[#{tag.inspect}]);"

        variables and variables[tag] = true
      when ?.
        # CSS escaped
        index = stack[-1][2][tag.inspect]

        source and source << "v&&r<<h.css_escape(v.is_a?(Array)?v[#{index}]:v[#{tag.inspect}]);"

        variables and variables[tag] = true
      when ?:
        # Defines start of a :section
        index = stack[-1][2][tag.inspect]

        stack_variables ||= 's=[];'
        stack << [ :section, tag, VariableTracker.new ]

        source and source << "if(v);s<<v;v=v.is_a?(Array)?v[#{index}]:(v.is_a?(Hash)&&v[#{tag.inspect}]);"
        source and source << "h.iterate(v){|v|;v=h.cast_as_vars(v, s);"
        
        sections and sections[tag] = true
      when ??
        # Defines start of a ?conditional
        
        stack[-1][2][tag.inspect]

        # The stack will inherit the variable assignment locations from the
        # existing stack layer.
        stack << [ :conditional, tag, stack[-1][2] ]
        source and source << "if(v&&v.is_a?(Hash)&&v[#{tag.inspect}]);"

        variables and variables[tag] = true
      when ?*
        source and source << "_t=t&&t[#{tag.inspect}];r<<(_t.respond_to?(:call)?_t.call(v,t):_t.to_s);"
        
        templates and templates[tag] = true
      when ?/
        # Closes out a section or conditional
        closed = stack.pop
        
        case (closed[0])
        when :section
          if (tag and tag != closed[1])
            raise ParseError, "Template contains unexpected {{#{tag}}}, expected {{#{closed[1]}}}"
          end
          
          source and source << "};v=s.pop;end;"
        when :conditional
          source and source << "end;"
        when :base
          raise ParseError, "Unexpected {{#{tag}}}, too many tags closed"
        end
      when ?=
        # Literal insertion
        index = stack[-1][2][tag.inspect]

        source and source << "v&&r<<(v.is_a?(Array)?v[#{index}]:v[#{tag.inspect}]).to_s;"

        variables and variables[tag] = true
      else
        # Contextual insertion
        index = stack[-1][2][tag.inspect]

        subst = "v.is_a?(Array)?v[#{stack[-1][2][tag.inspect]}]:v[#{tag.inspect}]"
        
        if (escape_method)
          source and source << "v&&r<<h.#{escape_method}(#{subst}.to_s);"
        else
          source and source << "v&&r<<(#{subst}).to_s;"
        end

        variables and variables[tag] = true
      end
    end
  end
  
  unless (stack.length == 1)
    case (stack[1][0])
    when :section
      raise ParseError, "Unclosed {{:#{stack[1][1]}}} in template"
    when :conditional
      raise ParseError, "Unclosed {{?#{stack[1][1]}}} in template"
    else
      raise ParseError, "Unclosed {{#{stack[1][1]}}} in template"
    end
  end
  
  if (source)
    source.replace("begin;c=false;h=Handlebar::Support;lambda{|v,t|raise RecursionError if(c);c=true;#{stack_variables}r='';#{source}c=false;r};end")
  end
  
  true
end

#marshal_dumpObject



267
268
269
# File 'lib/handlebar/template.rb', line 267

def marshal_dump
  [ @content, { :escape => @escape_method } ]
end

#marshal_load(dump) ⇒ Object



271
272
273
274
275
# File 'lib/handlebar/template.rb', line 271

def marshal_load(dump)
  @content, options = dump
  
  @escape_method = options[:escape]
end

#render(variables = nil, templates = nil, parents = nil) ⇒ Object Also known as: call



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/handlebar/template.rb', line 63

def render(variables = nil, templates = nil, parents = nil)
  variables =
    case (variables)
    when Array
      variables
    when Hash
      Hash[variables.collect { |k, v| [ k.to_sym, v ] }]
    else
      [ variables ]
    end
    
  if (templates)
    # Unless the template options have already been processed, mapping
    # will need to be performed.
    unless (templates.is_a?(TemplateHash))
      templates = TemplateHash[
        templates.collect do |k, v|
          [
            k,
            case (v)
            when Handlebar::Template, Proc, Array
              v
            when TOKEN_TRIGGER
              self.class.new(v, :escape => @escape_method)
            else
              v.to_s
            end
          ]
        end
      ]
    end
  else
    templates = TemplateHash.new
  end
  
  if (parents)
    case (parents)
    when Array
      _parents = parents.dup
      _parent = _parents.shift
      _parent.render(
        variables,
        templates.merge(
          nil => self.to_proc.call(variables, templates)
        ),
        _parents.empty? ? nil : _parents
      )
    when Handlebar::Template, Proc
      parents.render(
        variables,
        templates.merge(
          nil => self.to_proc.call(variables, templates)
        )
      )
    end
  else
    self.to_proc.call(variables, templates)
  end
end

#to_procObject



53
54
55
56
57
58
59
60
61
# File 'lib/handlebar/template.rb', line 53

def to_proc
  @_proc ||= begin
    source = ''

    self.compile(:source => source, :escape_method => @escape_method)

    eval(source)
  end
end

#to_yaml(dump) ⇒ Object



257
258
259
260
261
262
263
264
265
# File 'lib/handlebar/template.rb', line 257

def to_yaml(dump)
  _proc, @_proc = @_proc, nil
  
  super(dump)
  
  @_proc = _proc
  
  dump
end