tobi / liquid

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

This URL has Read+Write access

liquid / lib / liquid / tags / case.rb
100644 84 lines (62 sloc) 2.097 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
80
81
82
83
84
module Liquid
  class Case < Block
    Syntax = /(#{QuotedFragment})/
    WhenSyntax = /(#{QuotedFragment})(?:(?:\s+or\s+|\s*\,\s*)(#{QuotedFragment}.*))?/
 
    def initialize(tag_name, markup, tokens)
      @blocks = []
      
      if markup =~ Syntax
        @left = $1
      else
        raise SyntaxError.new("Syntax Error in tag 'case' - Valid syntax: case [condition]")
      end
            
      super
    end
 
    def unknown_tag(tag, markup, tokens)
      @nodelist = []
      case tag
      when 'when'
        record_when_condition(markup)
      when 'else'
        record_else_condition(markup)
      else
        super
      end
    end
 
    def render(context)
      context.stack do
        execute_else_block = true
        
        @blocks.inject([]) do |output, block|
      
          if block.else?
            
            return render_all(block.attachment, context) if execute_else_block
            
          elsif block.evaluate(context)
            
            execute_else_block = false
            output += render_all(block.attachment, context)
          end
      
          output
        end
      end
    end
    
    private
    
    def record_when_condition(markup)
      while markup
       # Create a new nodelist and assign it to the new block
       if not markup =~ WhenSyntax
       raise SyntaxError.new("Syntax Error in tag 'case' - Valid when condition: {% when [condition] [or condition2...] %} ")
       end
 
       markup = $2
 
       block = Condition.new(@left, '==', $1)
       block.attach(@nodelist)
       @blocks.push(block)
      end
    end
 
    def record_else_condition(markup)
 
      if not markup.strip.empty?
        raise SyntaxError.new("Syntax Error in tag 'case' - Valid else condition: {% else %} (no parameters) ")
      end
         
      block = ElseCondition.new
      block.attach(@nodelist)
      @blocks << block
    end
    
        
  end
  
  Template.register_tag('case', Case)
end