Skip to content

Commit

Permalink
Encode title and attributes of HTML tables (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Sep 11, 2023
1 parent f44a274 commit cfd6b45
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
12 changes: 8 additions & 4 deletions src/prettytable/prettytable.py
Expand Up @@ -2139,14 +2139,16 @@ def _get_simple_html_string(self, options):
open_tag = ["<table"]
if options["attributes"]:
for attr_name in options["attributes"]:
open_tag.append(f' {attr_name}="{options["attributes"][attr_name]}"')
open_tag.append(
f' {escape(attr_name)}="{escape(options["attributes"][attr_name])}"'
)
open_tag.append(">")
lines.append("".join(open_tag))

# Title
title = options["title"] or self._title
if title:
lines.append(f" <caption>{title}</caption>")
lines.append(f" <caption>{escape(title)}</caption>")

# Headers
if options["header"]:
Expand Down Expand Up @@ -2207,14 +2209,16 @@ def _get_formatted_html_string(self, options):
open_tag.append(' rules="cols"')
if options["attributes"]:
for attr_name in options["attributes"]:
open_tag.append(f' {attr_name}="{options["attributes"][attr_name]}"')
open_tag.append(
f' {escape(attr_name)}="{escape(options["attributes"][attr_name])}"'
)
open_tag.append(">")
lines.append("".join(open_tag))

# Title
title = options["title"] or self._title
if title:
lines.append(f" <caption>{title}</caption>")
lines.append(f" <caption>{escape(title)}</caption>")

# Headers
if options["header"]:
Expand Down
18 changes: 10 additions & 8 deletions tests/test_prettytable.py
Expand Up @@ -1070,13 +1070,13 @@ def test_HtmlOutputFormatted(self):

def test_HtmlOutputWithTitle(self):
t = helper_table()
t.title = "Title"
result = t.get_html_string()
t.title = "Title & Title"
result = t.get_html_string(attributes={"bgcolor": "red", "a<b": "1<2"})
assert (
result.strip()
== """
<table>
<caption>Title</caption>
<table bgcolor="red" a&lt;b="1&lt;2">
<caption>Title &amp; Title</caption>
<thead>
<tr>
<th>Field 1</th>
Expand Down Expand Up @@ -1107,13 +1107,15 @@ def test_HtmlOutputWithTitle(self):

def test_HtmlOutputFormattedWithTitle(self):
t = helper_table()
t.title = "Title"
result = t.get_html_string(format=True)
t.title = "Title & Title"
result = t.get_html_string(
attributes={"bgcolor": "red", "a<b": "1<2"}, format=True
)
assert (
result.strip()
== """
<table frame="box" rules="cols">
<caption>Title</caption>
<table frame="box" rules="cols" bgcolor="red" a&lt;b="1&lt;2">
<caption>Title &amp; Title</caption>
<thead>
<tr>
<th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 1</th>
Expand Down

0 comments on commit cfd6b45

Please sign in to comment.