Skip to content

Commit

Permalink
Merge pull request #2321 from mamhoff/allow-render-elements-to-take-b…
Browse files Browse the repository at this point in the history
…lock

Allow render_elements to take a block
  • Loading branch information
tvdeyen committed Apr 26, 2022
1 parent db7890a commit facf2ba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
13 changes: 7 additions & 6 deletions app/helpers/alchemy/elements_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ module ElementsHelper
# A class instance that will return elements that get rendered.
# Use this for your custom element loading logic in views.
#
def render_elements(options = {})
def render_elements(options = {}, &blk)
options = {
from_page: @page,
render_format: "html",
Expand All @@ -86,11 +86,12 @@ def render_elements(options = {})

elements = finder.elements(page_version: page_version)

buff = []
elements.each_with_index do |element, i|
buff << render_element(element, options, i + 1)
end
buff.join(options[:separator]).html_safe
default_rendering = ->(element, i) { render_element(element, options, i + 1) }
if block_given?
elements.map.with_index(&blk)
else
elements.map.with_index(&default_rendering)
end.join(options[:separator]).html_safe
end

# This helper renders a {Alchemy::Element} view partial.
Expand Down
12 changes: 12 additions & 0 deletions spec/helpers/alchemy/elements_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ module Alchemy
end
end

context "with a block" do
subject do
helper.render_elements(separator: ", ") do |element|
element.name
end
end

it "renders the block" do
is_expected.to eq("headline, article")
end
end

context "with from_page option" do
context "is a page object" do
let(:another_page) { create(:alchemy_page, :public) }
Expand Down

0 comments on commit facf2ba

Please sign in to comment.