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>

Defined Under Namespace

Classes: ParseTreeVisitor

Constant Summary collapse

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

Instance Attribute Summary collapse

Attributes inherited from Tag

#line_number, #nodelist, #parse_context, #tag_name

Instance Method Summary collapse

Methods inherited from Tag

#blank?, #name, #parse, parse, #raw

Methods included from ParserSwitching

#parse_with_selected_parser

Constructor Details

#initialize(tag_name, markup, options) ⇒ Cycle

Returns a new instance of Cycle.



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

def initialize(tag_name, markup, options)
  super
  case markup
  when NamedSyntax
    @variables = variables_from_string($2)
    @name = Expression.parse($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 Attribute Details

#variablesObject (readonly)

Returns the value of attribute variables.



18
19
20
# File 'lib/liquid/tags/cycle.rb', line 18

def variables
  @variables
end

Instance Method Details

#render(context) ⇒ Object



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

def render(context)
  context.registers[:cycle] ||= {}

  context.stack do
    key = context.evaluate(@name)
    iteration = context.registers[:cycle][key].to_i
    result = context.evaluate(@variables[iteration])
    iteration += 1
    iteration  = 0 if iteration >= @variables.size
    context.registers[:cycle][key] = iteration
    result
  end
end