Search code examples
pythonflaskjinja2jupyternbconvert

Flask and HTML Variables


I'm new to flask, but want to integrate some HTML capabilities from other libraries together with the templating power of flask. In playing around with variables, I'm not able to understand the different behavior for rendering HTML. Sometimes I can get the HTML rendered if I pass it directly to a view as a variable:

body = a bunch of HTML
@app.route('/')
def index():
    return '''
    {}
    '''.format(body)

However, if I try to pass this to a template using the {{ body }} variable, I don't get the HTML rendered. Instead, I will see the raw HTML on the page.

@app.route('/')
def index():
     return render_template("index.html", b = body)

In the "index.html" file, I call this with the {{ b }} template syntax. Here, I get the raw HTML though. I feel there's just one little piece I'm missing. Here's what I see for each approach respectively.

enter image description here

enter image description here


Solution

  • Jinja will escape all strings that it parses to avoid accidentally injecting HTML into your templates. To mark variables as "safe to use as-is", you need to use the safe template filter.

    {{ b|safe }}
    

    >>> b = '<a href="#">Example</a>'
    
    >>> render_template_string('{{ b }}', b=b)                                                
    '&lt;a href=&#34;#&#34;&gt;Example&lt;/a&gt;'
    
    >>> render_template_string('{{ b|safe }}')                                           
    '<a href="#">Example</a>'