Implemented reversed flag on for loops {% for a in b reversed %}

This commit is contained in:
Tobias Lütke
2008-05-08 17:17:41 -04:00
parent 8f45647aa3
commit 63f9a05223
2 changed files with 15 additions and 5 deletions
+10 -5
View File
@@ -20,7 +20,9 @@ module Liquid
# #
# {% for item in collection limit:5 offset:10 %} # {% for item in collection limit:5 offset:10 %}
# {{ item.name }} # {{ item.name }}
# {% end %} # {% end %}
#
# To reverse the for loop simply use {% for item in collection reversed %}
# #
# == Available variables: # == Available variables:
# #
@@ -40,13 +42,14 @@ module Liquid
# forloop.last:: Returns true if the item is the last item. # forloop.last:: Returns true if the item is the last item.
# #
class For < Block class For < Block
Syntax = /(\w+)\s+in\s+(#{VariableSignature}+)/ Syntax = /(\w+)\s+in\s+(#{VariableSignature}+)\s*(reversed)?/
def initialize(tag_name, markup, tokens) def initialize(tag_name, markup, tokens)
if markup =~ Syntax if markup =~ Syntax
@variable_name = $1 @variable_name = $1
@collection_name = $2 @collection_name = $2
@name = "#{$1}-#{$2}" @name = "#{$1}-#{$2}"
@reversed = $3
@attributes = {} @attributes = {}
markup.scan(TagAttributes) do |key, value| markup.scan(TagAttributes) do |key, value|
@attributes[key] = value @attributes[key] = value
@@ -80,10 +83,12 @@ module Liquid
return '' if segment.empty? return '' if segment.empty?
segment.reverse! if @reversed
result = [] result = []
length = segment.length length = segment.length
# Store our progress through the collection for the continue flag # Store our progress through the collection for the continue flag
context.registers[:for][@name] = from + segment.length context.registers[:for][@name] = from + segment.length
+5
View File
@@ -376,6 +376,11 @@ HERE
assert_template_result('', '{% if null == true %}?{% endif %}', {}) assert_template_result('', '{% if null == true %}?{% endif %}', {})
end end
def test_for_reversed
assigns = {'array' => [ 1, 2, 3] }
assert_template_result('321','{%for item in array reversed %}{{item}}{%endfor%}',assigns)
end
def test_ifchanged def test_ifchanged
assigns = {'array' => [ 1, 1, 2, 2, 3, 3] } assigns = {'array' => [ 1, 1, 2, 2, 3, 3] }
assert_template_result('123','{%for item in array%}{%ifchanged%}{{item}}{% endifchanged %}{%endfor%}',assigns) assert_template_result('123','{%for item in array%}{%ifchanged%}{{item}}{% endifchanged %}{%endfor%}',assigns)