I cannot render html in python 3

Asked

Viewed 194 times

0

I have the following app:

#!/usr/bin/python3

from bottle import template, route, run
import html
cabeca = ('''
<html lang="pt-br">
    <head>
    </head>
    <body>

        <nav id="menu">
            {{menu}}
        </nav>

        <main id="conteudo">
            {{conteudo}}
        </main>

    </body>
</html>
''')
menu = (('add', 'flaticon-add', 'Adicionar'),
('busca', 'flaticon-target', 'Buscar'),
('balanco', 'flaticon-coin', 'Balanço'),
('conf', 'flaticon-settings', 'Configurações'))

def cria_menu():
    bloco = ('<nav id="menu">')
    for item in menu:
        bloco += ('<div class="menu-item">\
        <a class="menu-link" href="{}">\
        <img class="{} menu-icon" alt="{}"/>\
        </a>\
        </div>\
        '.format(item[0], item[1], item[2]))
    bloco += ('</nav>')
    return(bloco)

@route('/')
def index():
    return(template(cabeca, menu = html.unescape(cria_menu())\
    .replace('&lt;', '<')\
    .replace('&gt;', '>')\
    .replace('&quot;', '"'), conteudo = 'Alguma coisa'))

run(port = 8000, debug = True, reloader = True)

No matter what I do, I can’t render the page.

  • 2

    Returns an error ? It is important to add information to help resolve your problem or question. You can do this editing your question.

  • As already mentioned, it would be of utmost importance to provide error output, debugging you can see this. I ran your file on Python3 and making explicit the import of unescape: from html import unescape and returned me a text output with the html mounted.

1 answer

1


The problem is that the syntax {{ variavel }} exists to include common text in your HTML, not to include more HTML code. This syntax causes Bottle to automatically "escape" the entire contents of the variable so that it appears in the result as it is, and prevent XSS attacks if the variable comes from the user.

To include one template in the other, the correct one would be to use include() or rebase() as in the example of documentation.

But for a quick test, you can include the exclamation ! before the variable name, which forces Bottle not to "escape" the content and leave it as is:

    <nav id="menu">
        {{!menu}}
    </nav>

    <main id="conteudo">
        {{!conteudo}}
    </main>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.