How to add extracted html in yattag?

2.3k views Asked by At

I am trying to create html via yattag. Only problem is, the header file I use from another html file, so I read that file and try to insert that as header. Here is the problem. Though I pass unescaped html string, yattag escapes it. That is it converts '<' to &lt; while adding to html string.

MWE:

from yattag import Doc, indent
import html 
doc, tag, text = Doc().tagtext()


h = open(nbheader_template, 'r')
h_content= h.read()
h_content = html.unescape(h_content)

doc.asis('<!DOCTYPE html>')
with tag('html'):

    # insert dummy head
    with tag('head'):
        text(h_content)  # just some dummy text to replace later - workaround for now

    with tag('body'):
        # insert as many divs as no of files
        for i in range(counter):
            with tag('div', id = 'divID_'+ str(1)):
                text('Div Page: ' + str(i))

result = indent(doc.getvalue())



# inject raw head - dirty workaround as yattag not doing it
# result = result.replace('<head>headtext</head>',h_content)

with open('test.html', "w") as file:
    file.write(result)

Output:
enter image description here

Context: I am trying to combine multiple jupyter python notebooks, in to a single html, that is why heavy header. The header content (nbheader_template) could be found here

2

There are 2 answers

2
elbrant On

I'm not fully fluent in 'yattag', but the one thing I see missing is:

 with tag('body'):

The code you have quoted (above) is placing <div> and text into your header, where it clearly doesn't belong.

0
H6_ On

If you want to prevent the escaping you have to use doc.asis instead of text.

The asis methods appends a string to the document without any form of escaping.

See also the documentation.