Search code examples
pythonhtml

How to render raw html in the PyHTML library


I am not able to render a table generated by the pandas .tohtml() function into my pyhtml generated code.

s = h.html(
            h.head(
                h.title("Student Data")
            ),
            h.body(
                h.h1(
                    "Student Details"
                ),
                (sdf.to_html(index=False))
            )
        )

This is what I tried, ends up giving me the table as a string. Heard about a raw() method, but the current version just says its not existent.

<table border="1" class="dataframe">
<thead> <tr style="text-align: right;"> 
<th>Student id</th> <th>Course id</th> <th>Marks</th> </tr> 
</thead> 
<tbody> 
<tr> <td>1002</td> <td>2001</td> <td>67</td> </tr> 
</tbody> 
</table> 

This is the approx structure of my html table


Solution

  • Be careful though! PyHTML escapes these sequences for good reason, so don't do this unless you have a very good reason, and are certain that your text is trusted.

    You can enclose the output from sdf.to_html() in div or span tag and pass _safe=True, e.g.

    import pyhtml as h
    from pandas import DataFrame
    
    
    sdf = DataFrame(data = {'Student id': [1002], 'Course id': [2001], 'Marks':[67]})
    
    s = h.html(
                h.head(
                    h.title("Student Data")
                ),
                h.body(
                    h.h1(
                        "Student Details"
                    ),
                    h.div(sdf.to_html(index=False), _safe=True))
            )
    
    print(s.render())
    

    output:

    <!DOCTYPE html>
    <html>
      <head>
        <title>
          Student Data
        </title>
      </head>
      <body>
        <h1>
          Student Details
        </h1>
        <div>
          <table border="1" class="dataframe">
            <thead>
              <tr style="text-align: right;">
                <th>Student id</th>
                <th>Course id</th>
                <th>Marks</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>1002</td>
                <td>2001</td>
                <td>67</td>
              </tr>
            </tbody>
          </table>
        </div>
      </body>
    </html>
    

    Alternatively, you can use pyhtml-enhanced package instead. There is DangerousRawHtml. See Embedding raw HTML

    import pyhtml as h
    from pandas import DataFrame
    
    
    sdf = DataFrame(data = {'Student id': [1002], 'Course id': [2001], 'Marks':[67]})
    
    s = h.html(
                h.head(
                    h.title("Student Data")
                ),
                h.body(
                    h.h1(
                        "Student Details"
                    ),
                    h.DangerousRawHtml(sdf.to_html(index=False))
                )
            )
    
    print(s.render())