Sha256: 2c6cc7e3485e15e3be8049d9ee62527f410d97dc44bbe7de021bd96d881d5257

Contents?: true

Size: 1.61 KB

Versions: 8

Compression:

Stored size: 1.61 KB

Contents

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}+/o
    NamedSyntax  = /^(#{QuotedFragment})\s*\:\s*(.*)/o
  
    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*/o
    	  $1 ? $1 : nil
    	end.compact
    end
  
  end
  
  Template.register_tag('cycle', Cycle)
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
liquid-2.5.5 lib/liquid/tags/cycle.rb
liquid-2.5.4 lib/liquid/tags/cycle.rb
liquid-2.5.3 lib/liquid/tags/cycle.rb
liquid-2.5.1 lib/liquid/tags/cycle.rb
wordify_liquid-2.5.1 lib/liquid/tags/cycle.rb
liquid-2.5.0 lib/liquid/tags/cycle.rb
liquid-2.4.1 lib/liquid/tags/cycle.rb
liquid-2.4.0 lib/liquid/tags/cycle.rb