added break and continue tags

This commit is contained in:
Jon Daniel
2012-08-21 00:00:02 -04:00
parent bf86459456
commit 484fd18612
5 changed files with 83 additions and 5 deletions
+5
View File
@@ -8,4 +8,9 @@ module Liquid
class StandardError < Error; end
class SyntaxError < Error; end
class StackLevelError < Error; end
class Interrupt < Error; end
class BreakInterrupt < Interrupt; end
class ContinueInterrupt < Interrupt; end
end
+24
View File
@@ -0,0 +1,24 @@
module Liquid
# Break tag to be used to break out of a for loop.
#
# == Basic Usage:
# {% for item in collection %}
# {% if item.condition %}
# {% break %}
# {% endif %}
# {% endfor %}
#
class Break < Tag
##
# Add an interrupt to context errors so a for loop can check
# for interrupts.
def render(context)
context.handle_error(BreakInterrupt.new)
end
end
Template.register_tag('break', Break)
end
+24
View File
@@ -0,0 +1,24 @@
module Liquid
# Continue tag to be used to break out of a for loop.
#
# == Basic Usage:
# {% for item in collection %}
# {% if item.condition %}
# {% continue %}
# {% endif %}
# {% endfor %}
#
class Continue < Tag
##
# Add an interrupt to context errors so a for loop can check
# for interrupts.
def render(context)
context.handle_error(ContinueInterrupt.new)
end
end
Template.register_tag('continue', Continue)
end
+13 -1
View File
@@ -114,7 +114,19 @@ module Liquid
'first' => (index == 0),
'last' => (index == length - 1) }
result << render_all(@for_block, context)
rendered = render_all(@for_block, context)
if context.errors.last.is_a? BreakInterrupt
context.errors.pop
break
end
if context.errors.last.is_a? ContinueInterrupt
context.errors.pop
next
end
result << rendered
end
end
result
+13
View File
@@ -168,6 +168,19 @@ HERE
assert_template_result(expected,markup,assigns)
end
def test_break
assigns = {'array' => {'items' => [1,2,3,4,5,6,7,8,9,10]}}
markup = '{% for i in array.items %}{{ i }}{% if i > 3 %}{% break %}{% endif %}{% endfor %}'
expected = "123"
assert_template_result(expected,markup,assigns)
end
def test_continue
assigns = {'array' => {'items' => [1,2,3,4,5]}}
markup = '{% for i in array.items %}{% if i == 3 %}{% continue %}{% else %}{{ i }}{% endif %}{% endfor %}'
expected = "1245"
assert_template_result(expected,markup,assigns)
end
def test_for_tag_string
# ruby 1.8.7 "String".each => Enumerator with single "String" element.