Skip to content

Commit 661957b

Browse files
authored
Add support for CDATA sections in SVGs (#873)
After this, no one can say Phlex is a leaky abstraction for HTML. It will be a 100% airtight abstraction for valid HTML5 structures. FWIW, I’ve never used `CDATA` sections before and I’ve never heard of anyone else using them.
1 parent fdd7c02 commit 661957b

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

browser_tests.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,10 @@ def view_template
105105
File.open("fixtures/xss.txt") do |file|
106106
file.each_line do |line|
107107
div(class: line) { line }
108+
svg do |s|
109+
s.cdata(line)
110+
s.cdata { line }
111+
end
108112
end
109113
end
110114
end

lib/phlex/svg.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,20 @@ def filename
1515
nil
1616
end
1717

18+
def cdata(content = nil, &block)
19+
state = @_state
20+
return unless state.should_render?
21+
22+
if !block && String === content
23+
state.buffer << "<![CDATA[" << content.gsub("]]>", "]]>]]<![CDATA[") << "]]>"
24+
elsif block && nil == content
25+
state.buffer << "<![CDATA[" << capture(&block).gsub("]]>", "]]>]]<![CDATA[") << "]]>"
26+
else
27+
28+
raise Phlex::ArgumentError.new("Expected a String or block.")
29+
end
30+
end
31+
1832
def tag(name, **attributes, &)
1933
state = @_state
2034
block_given = block_given?

quickdraw/svg.test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,25 @@ def view_template
1616
component = Class.new(Phlex::SVG)
1717
assert_equal component.new.content_type, "image/svg+xml"
1818
end
19+
20+
test "cdata with string" do
21+
component = Class.new(Phlex::SVG) do
22+
def view_template
23+
cdata("Hello, <[[test]]> World!")
24+
end
25+
end
26+
27+
assert_equal component.call, %(<![CDATA[Hello, <[[test]]>]]<![CDATA[ World!]]>)
28+
end
29+
30+
test "cdata with block" do
31+
component = Class.new(Phlex::SVG) do
32+
def view_template
33+
cdata do
34+
path(d: "123")
35+
end
36+
end
37+
end
38+
39+
assert_equal component.call, %(<![CDATA[<path d="123"></path>]]>)
40+
end

0 commit comments

Comments
 (0)