public
Description: Liquid markup language. Save, customer facing template language for flexible web apps.
Homepage: http://www.liquidmarkup.org
Clone URL: git://github.com/tobi/liquid.git
Click here to lend your support to: liquid and make a donation at www.pledgie.com !
liquid / lib / liquid / tags / cycle.rb
100644 59 lines (51 sloc) 1.656 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
module Liquid
  
  # Cycle is usually used within a loop to alternate between values, like colors or DOM classes.
  #
  # {% for item in items %}
  # <div class="{% cycle 'red', 'green', 'blue' %}"> {{ item }} </div>
  # {% end %}
  #
  # <div class="red"> Item one </div>
  # <div class="green"> Item two </div>
  # <div class="blue"> Item three </div>
  # <div class="red"> Item four </div>
  # <div class="green"> Item five</div>
  #
  class Cycle < Tag
    SimpleSyntax = /^#{QuotedFragment}+/
    NamedSyntax = /^(#{QuotedFragment})\s*\:\s*(.*)/
  
    def initialize(tag_name, markup, tokens)
      case markup
      when NamedSyntax
       @variables = variables_from_string($2)
       @name = $1
      when SimpleSyntax
        @variables = variables_from_string(markup)
       @name = "'#{@variables.to_s}'"
      else
        raise SyntaxError.new("Syntax Error in 'cycle' - Valid syntax: cycle [name :] var [, var2, var3 ...]")
      end
      super
    end
  
    def render(context)
      context.registers[:cycle] ||= Hash.new(0)
    
      context.stack do
        key = context[@name]
        iteration = context.registers[:cycle][key]
        result = context[@variables[iteration]]
        iteration += 1
        iteration = 0 if iteration >= @variables.size
        context.registers[:cycle][key] = iteration
        result
      end
    end
  
    private
  
    def variables_from_string(markup)
      markup.split(',').collect do |var|
     var =~ /\s*(#{QuotedFragment})\s*/
     $1 ? $1 : nil
     end.compact
    end
  
  end
  
  Template.register_tag('cycle', Cycle)
end