Skip to content

Commit

Permalink
Avoid panic when parsing contents with templates (#142)
Browse files Browse the repository at this point in the history
* Avoid panic when parsing contents with templates

This is not getting the contents of templates, but is parsing with an
empty "template" tag.

Closes #120

* Fix clippy issue
  • Loading branch information
philss authored Mar 25, 2024
1 parent 515daa0 commit ee1dedd
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
16 changes: 14 additions & 2 deletions native/html5ever_nif/src/flat_dom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,20 @@ impl TreeSink for FlatSink {
fn get_document(&mut self) -> Self::Handle {
NodeHandle(0)
}
fn get_template_contents(&mut self, _target: &Self::Handle) -> Self::Handle {
panic!("Templates not supported");
fn get_template_contents(&mut self, target: &Self::Handle) -> Self::Handle {
// Inspired in https://github.com/servo/html5ever/blob/1a62a39879a1def200dcb87b900265993e6c1c83/rcdom/lib.rs#L235
// It is not getting the templates contents. But is printing the empty tag.
// TODO: print the contents as text.
let node = self.node(*target);
if let NodeData::Element {
ref template_contents,
..
} = node.data
{
*template_contents.as_ref().expect("not a template element!")
} else {
panic!("not a template element!")
}
}

fn same_node(&self, x: &Self::Handle, y: &Self::Handle) -> bool {
Expand Down
29 changes: 29 additions & 0 deletions test/html5ever_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -279,4 +279,33 @@ defmodule Html5everTest do
]}
]} = parsed
end

test "parse html with a template tag ignores template content" do
html = """
<!doctype html>
<html>
<head><title>With template</title></head>
<body>
<h1>Document</h1>
<template>
<h2>Flower</h2>
<img src="img_white_flower.jpg" width="214" height="204">
</template>
</body>
</html>
"""

assert Html5ever.parse(html) ==
{:ok,
[
{:doctype, "html", "", ""},
{"html", [],
[
{"head", [], [{"title", [], ["With template"]}]},
"\n",
{"body", [],
["\n", {"h1", [], ["Document"]}, "\n", {"template", [], []}, "\n", "\n", "\n"]}
]}
]}
end
end

0 comments on commit ee1dedd

Please sign in to comment.