A.S A.S - 6 months ago 36
Python Question

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.

Answer

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">
  {{text|safe}}
  {% include 'your_form.html' %}
 </div>