Skip to content

Commit

Permalink
Build HTML and SVG with an inline DSL (#860)
Browse files Browse the repository at this point in the history
Co-authored-by: Marco Roth <[email protected]>
Co-authored-by: Will Cosgrove <[email protected]>
  • Loading branch information
3 people authored Feb 14, 2025
1 parent 41a58c8 commit 168ad4b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/phlex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,36 @@ def self.eager_load
end
end
end

def self.html(&block)
HTML.call do |component|
receiver = block.binding.receiver

receiver.instance_variables.each do |ivar|
next if component.instance_variable_defined?(ivar)

value = receiver.instance_variable_get(ivar)
component.instance_variable_set(ivar, value)
end

component.instance_exec(receiver, &block)
end
end

def self.svg(&block)
SVG.call do |component|
receiver = block.binding.receiver

receiver.instance_variables.each do |ivar|
next if component.instance_variable_defined?(ivar)

value = receiver.instance_variable_get(ivar)
component.instance_variable_set(ivar, value)
end

component.instance_exec(receiver, &block)
end
end
end

def 💪
Expand Down
28 changes: 28 additions & 0 deletions quickdraw/inline.test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

test "inline html with no param" do
output = Phlex.html do
h1 { "Hi" }
end

assert_equal_html output, <<~HTML.strip
<h1>Hi</h1>
HTML
end

def title = "Hello"

test "inline html with a yield param" do
@ivar = "Hi"
h1 = "foo"

output = Phlex.html do |receiver|
h1 { h1 }
h1 { @ivar }
title { receiver.title }
end

assert_equal_html output, <<~HTML.strip
<h1>foo</h1><h1>Hi</h1><title>Hello</title>
HTML
end

0 comments on commit 168ad4b

Please sign in to comment.