Skip to content

Commit

Permalink
[New Feature] Add forloop inside render tag when using for syntax (#1191
Browse files Browse the repository at this point in the history
)

* Add forloop to render for syntax

* Remove forloop guard
  • Loading branch information
shopmike committed Oct 17, 2019
1 parent 1223444 commit 3784020
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/liquid/tags/render.rb
Expand Up @@ -43,19 +43,26 @@ def render_tag(context, output)

context_variable_name = @alias_name || template_name.split('/').last

render_partial_func = ->(var) {
render_partial_func = ->(var, forloop) {
inner_context = context.new_isolated_subcontext
inner_context.template_name = template_name
inner_context.partial = true
inner_context['forloop'] = forloop if forloop
@attributes.each do |key, value|
inner_context[key] = context.evaluate(value)
end
inner_context[context_variable_name] = var unless var.nil?
partial.render_to_output_buffer(inner_context, output)
forloop&.send(:increment!)
}

variable = @variable_name_expr ? context.evaluate(@variable_name_expr) : nil
variable.is_a?(Array) ? variable.each(&render_partial_func) : render_partial_func.call(variable)
if variable.is_a?(Array)
forloop = Liquid::ForloopDrop.new(template_name, variable.count, nil)
variable.each { |var| render_partial_func.call(var, forloop) }
else
render_partial_func.call(variable, nil)
end

output
end
Expand Down
9 changes: 9 additions & 0 deletions test/integration/tags/render_tag_test.rb
Expand Up @@ -205,4 +205,13 @@ def test_render_tag_for
assert_template_result("Product: Draft 151cm Product: Element 155cm ",
"{% render 'product' for products %}", "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }])
end

def test_render_tag_forloop
Liquid::Template.file_system = StubFileSystem.new(
'product' => "Product: {{ product.title }} {% if forloop.first %}first{% endif %} {% if forloop.last %}last{% endif %} index:{{ forloop.index }} ",
)

assert_template_result("Product: Draft 151cm first index:1 Product: Element 155cm last index:2 ",
"{% render 'product' for products %}", "products" => [{ 'title' => 'Draft 151cm' }, { 'title' => 'Element 155cm' }])
end
end

0 comments on commit 3784020

Please sign in to comment.