tobi / liquid

Liquid markup language. Save, customer facing template language for flexible web apps.

This URL has Read+Write access

liquid / lib / liquid / variable.rb
100644 52 lines (46 sloc) 1.399 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
module Liquid
 
  # Holds variables. Variables are only loaded "just in time"
  # and are not evaluated as part of the render stage
  #
  # {{ monkey }}
  # {{ user.name }}
  #
  # Variables can be combined with filters:
  #
  # {{ user | link }}
  #
  class Variable
    attr_accessor :filters, :name
 
    def initialize(markup)
      @markup = markup
      @name = nil
      @filters = []
      if match = markup.match(/\s*(#{QuotedFragment})/)
        @name = match[1]
        if markup.match(/#{FilterSeparator}\s*(.*)/)
          filters = Regexp.last_match(1).split(/#{FilterSeparator}/)
          filters.each do |f|
            if matches = f.match(/\s*(\w+)/)
              filtername = matches[1]
              filterargs = f.scan(/(?:#{FilterArgumentSeparator}|#{ArgumentSeparator})\s*(#{QuotedFragment})/).flatten
              @filters << [filtername.to_sym, filterargs]
            end
          end
        end
      end
    end
 
    def render(context)
      return '' if @name.nil?
      @filters.inject(context[@name]) do |output, filter|
        filterargs = filter[1].to_a.collect do |a|
          context[a]
        end
        begin
          context.invoke(filter[0], output, *filterargs)
        rescue FilterNotFound
          raise FilterNotFound, "Error - filter '#{filter[0]}' in '#{@markup.strip}' could not be found."
        end
      end
    end
 
 
  end
end