Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Selective capture blocks #702

Merged
merged 1 commit into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/phlex/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,17 @@ def end_target
def capturing_into(new_buffer)
original_buffer = @buffer
original_capturing = @capturing
original_fragments = @fragments

begin
@buffer = new_buffer
@capturing = true
@fragments = nil
yield
ensure
@buffer = original_buffer
@capturing = original_capturing
@fragments = original_fragments
end

new_buffer
Expand Down
5 changes: 4 additions & 1 deletion lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ def unsafe_raw(content = nil)
def capture(&block)
return "" unless block

@_context.capturing_into(+"") { yield_content(&block) }
context = @_context
return if context.fragments && !context.in_target_fragment

context.capturing_into(+"") { yield_content(&block) }
end

private
Expand Down
32 changes: 32 additions & 0 deletions test/phlex/selective_rendering.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,18 @@ def view_template
end
end

class WithCaptureBlock < Phlex::HTML
def view_template
h1(id: "before") { "Before" }
div(id: "around") do
capture do
h1(id: "inside") { "Inside" }
end
end
h1(id: "after") { "After" }
end
end

describe Phlex::HTML do
it "renders the just the target fragment" do
expect(
Expand All @@ -78,4 +90,24 @@ def view_template
StandardElementExample.new(checker).call(fragments: ["target"])
expect(called).to be == false
end

describe "with a capture block" do
it "doesn't render the capture block" do
expect(
WithCaptureBlock.new.call(fragments: ["after"])
).to be == %(<h1 id="after">After</h1>)
end

it "renders the capture block when selected" do
expect(
WithCaptureBlock.new.call(fragments: ["around"])
).to be == %(<div id="around">&lt;h1 id=&quot;inside&quot;&gt;Inside&lt;/h1&gt;</div>)
end

it "doesn't select from the capture block" do
expect(
WithCaptureBlock.new.call(fragments: ["inside"])
).to be == ""
end
end
end