Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to insert HTML into Flask

I know how to send some plain text from Python with render_template when a URL is visited:

@app.route(/success.html")
...
return render_template("index.html", text="This text goes inside the HTML")

And the template would have something like this:

<div class="output">
  {{text|safe}}
 </div>

However, I am not sure what to do when I need to insert a few lines of HTML. For example, a form:

<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

It will probably work if I load this as a string in the Python script and send it to the template, but that doesn't sound quite right.

Anyone knows how to properly insert HTML into a Flask webpage? A dummy example would also be great.

like image 852
multigoodverse Avatar asked May 19 '16 07:05

multigoodverse


1 Answers

I want to figure out how to insert a HTML snippet into an existing template...

You can use the Jinja2 {% include %} directive.

{% include 'your_form.html' %}

... and where to store that snippet.

So you'd put your form in a template of its own, called your_form.html with the content:

<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

then in your index.html include it

<div class="output">
  {% include 'your_form.html' %}
 </div>

Dynamic variables in Jinja2

I want to render it dynamically.

Quoting from the docs

If you access variables inside tags don’t put the braces around them.

So simply:

{% include html_file %}

If you're using older versions, here's a simple way

{% include '%s' % html_file %}

Just to illustrate the flexibility of it, here's some examples to give you inspiration

{% include '%s.html' % name_without_extension %}
{% include 'templates/%s/forms/%s' % (company, template) %}

You can also set a Jinja variable like this (it's more verbose IMO)

{% set template_path = html_file %}
{% include template_path %}

Security tip: Make sure you know exactly what is passed on as the variable html_file, since it's dynamic, if that value comes from the client, you may be exposing your own files

like image 108
bakkal Avatar answered Sep 25 '22 13:09

bakkal