Add HTML formatted Caption for PrettyTable Title

39 Views Asked by At

I am trying to render an HTML table using PrettyTable python package. I need to have HTML formatted caption for the table but for some reason PrettyTable is replacing < with &lt;, " with &quot; and > with &gt;

Below is my code snippet:

>>> from prettytable import PrettyTable
>>> table = PrettyTable()
>>> table.field_names = ["Name", "Email", "Phone"]
>>> table.add_row(["John Smith", "[email protected]", "XXX-XXX-XXXX"])
>>> table
+------------+----------------------+--------------+
|    Name    |        Email         |    Phone     |
+------------+----------------------+--------------+
| John Smith | [email protected] | XXX-XXX-XXXX |
+------------+----------------------+--------------+
>>> print(table.get_html_string(title='<a href="www.example.com">Table</a>'))
<table>
    <caption>&lt;a href=&quot;www.example.com&quot;&gt;Table&lt;/a&gt;</caption>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John Smith</td>
            <td>[email protected]</td>
            <td>XXX-XXX-XXXX</td>
        </tr>
    </tbody>
</table>
>>>

How can I make PrettyTable to render the HTML formatted title properly?

1

There are 1 best solutions below

0
Bijesh Mohan On

This Answer helped me to find the solution!

Below is my solution:

>>> import html
>>> from prettytable import PrettyTable
>>> table = PrettyTable()
>>> table.field_names = ["Name", "Email", "Phone"]
>>> table.add_row(["John Smith", "[email protected]", "XXX-XXX-XXXX"])
>>> table
+------------+----------------------+--------------+
|    Name    |        Email         |    Phone     |
+------------+----------------------+--------------+
| John Smith | [email protected] | XXX-XXX-XXXX |
+------------+----------------------+--------------+
>>> unescaped = html.unescape(table.get_html_string(title='<a href="www.example.com">Table</a>'))
>>> print(unescaped)
<table>
    <caption><a href="www.example.com">Table</a></caption>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John Smith</td>
            <td>[email protected]</td>
            <td>XXX-XXX-XXXX</td>
        </tr>
    </tbody>
</table>
>>>