Skip to content

Add support for CDATA sections in SVGs #873

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

Merged
merged 1 commit into from
Mar 4, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions browser_tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ def view_template
File.open("fixtures/xss.txt") do |file|
file.each_line do |line|
div(class: line) { line }
svg do |s|
s.cdata(line)
s.cdata { line }
end
end
end
end
Expand Down
14 changes: 14 additions & 0 deletions lib/phlex/svg.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ def filename
nil
end

def cdata(content = nil, &block)
state = @_state
return unless state.should_render?

if !block && String === content
state.buffer << "<![CDATA[" << content.gsub("]]>", "]]>]]<![CDATA[") << "]]>"
elsif block && nil == content
state.buffer << "<![CDATA[" << capture(&block).gsub("]]>", "]]>]]<![CDATA[") << "]]>"
else

raise Phlex::ArgumentError.new("Expected a String or block.")
end
end

def tag(name, **attributes, &)
state = @_state
block_given = block_given?
Expand Down
22 changes: 22 additions & 0 deletions quickdraw/svg.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,25 @@ def view_template
component = Class.new(Phlex::SVG)
assert_equal component.new.content_type, "image/svg+xml"
end

test "cdata with string" do
component = Class.new(Phlex::SVG) do
def view_template
cdata("Hello, <[[test]]> World!")
end
end

assert_equal component.call, %(<![CDATA[Hello, <[[test]]>]]<![CDATA[ World!]]>)
end

test "cdata with block" do
component = Class.new(Phlex::SVG) do
def view_template
cdata do
path(d: "123")
end
end
end

assert_equal component.call, %(<![CDATA[<path d="123"></path>]]>)
end