Class: Liquid::Cycle

Inherits:
Tag
  • Object
show all
Defined in:
lib/liquid/tags/cycle.rb

Overview

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>

Constant Summary

SimpleSyntax =
/\A#{QuotedFragment}+/o
NamedSyntax =
/\A(#{QuotedFragment})\s*\:\s*(.*)/om

Instance Attribute Summary

Attributes inherited from Tag

#nodelist, #options, #warnings

Instance Method Summary collapse

Methods inherited from Tag

#name, parse, #parse, #parse_with_selected_parser

Constructor Details

#initialize(tag_name, markup, options) ⇒ Cycle



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/liquid/tags/cycle.rb', line 18

def initialize(tag_name, markup, options)
  super
  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(options[:locale].t("errors.syntax.cycle".freeze))
  end
end

Instance Method Details

#blank?Boolean



46
47
48
# File 'lib/liquid/tags/cycle.rb', line 46

def blank?
  false
end

#render(context) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/liquid/tags/cycle.rb', line 32

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