首页 > 解决方案 > Flask's url_for function does not get interpolated within html code

问题描述

@app.route( '/log=<page>' )
def log( page ):
....
....
# add counter to html template and start rendering
counter = '''<center>
            <table bgcolor=black bordercolor=orangered>
                <td><font size=3 color=lime> Αριθμός Επισκεπτών     </font></td>
                <td><a href="http://superhost.gr/log=%s">       <font size=3 color=plum> %d </font></a></td>
            </table>
        ''' % (page, pagehit)

Why the above code cannot be written as follows. It doesn't get interpolated.

# add counter to html template and start rendering
counter = '''<center>
            <table bgcolor=black bordercolor=orangered>
                <td><font size=3 color=lime> Αριθμός Επισκεπτών     </font></td>
                <td><a href="<a href="{{ url_for('/log', page='%s' }}">">   <font size=3 color=plum> %d </font></a></td>
            </table>
        ''' % (page, pagehit)    

Also when i try an inline statement to avoid for block i get an error. It should have worked.

name = nikos if (5>3)

标签: pythonflask

解决方案


You can either pass the variable to the template and have the {{url_for inside your template, then the rendering engine will take care of that IIRC (RECOMMENDED)

Or you can evaluate it like:

counter = '''<center>
            <table bgcolor=black     bordercolor=orangered>
                <td><font size=3 color=lime> Αριθμός Επισκεπτών     </font></td>
                <td><a href="{url}">   <font size=3 color=plum> {number} </font></a></td>
            </table>
    '''.format(url={{ url_for('/log', page=page) }}, number=pagehit)

Also you have a bug in the second code you post it says

<a href="<a href="{{ url_for('/log', page='%s' }}">"> 

推荐阅读