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.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With