Proper way to insert HTML into Flask

2024/10/6 6:40:32

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">{% 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

https://en.xdnf.cn/q/70399.html

Related Q&A

How to add a new class to an existing classifier in deep learning?

I trained a deep learning model to classify the given images into three classes. Now I want to add one more class to my model. I tried to check out "Online learning", but it seems to train on…

Count unique elements along an axis of a NumPy array

I have a three-dimensional array likeA=np.array([[[1,1], [1,0]],[[1,2], [1,0]],[[1,0], [0,0]]])Now I would like to obtain an array that has a nonzero value in a given position if only a unique nonzero …

influxdb python: 404 page not found

I am trying to use the influxdb-python lib which I found here. But I cant even get the tutorial programm to work. When I run the following example code:$ python>>> from influxdb import InfluxD…

Django Table already exist

Here is my Django Migration file. When I run python manage.py makemigrations/migrate I get this error.Error:-django.db.utils.OperationalError: (1050, "Table tickets_duration already exists")I…

Python round() too slow, faster way to reduce precision?

I am doing the following:TOLERANCE = 13 some_float = ... round(some_float, TOLERANCE)This is run many times, so performance is important. I have to round some_float due to floating point representation…

Reading .doc file in Python using antiword in Windows (also .docx)

I tried reading a .doc file like - with open(file.doc, errors=ignore) as f:text = f.read()It did read that file but with huge junk, I cant remove that junk as I dont know from where it starts and where…

Error installing package with pip

Im trying to install a charting tool (matplotlib-v1.4.2) for python 3.4 in Windows 7, so far all my trails doesnt seem to do the job.Attempts:Ive downloaded pip from GitHub python -m pip install matplo…

Assign new values to certain tensor elements in Keras

I need to change the value of some elements of a tensor. I know what elements -- they are in a boolean tensor already.I dont see how to do this in keras code. But if I were using TensorFlow code I woul…

Making grid triangular mesh quickly with Numpy

Consider a regular matrix that represents nodes numbered as shown in the figure:I want to make a list with all the triangles represented in the figure. Which would result in the following 2 dimensional…

df [X].unique() and TypeError: unhashable type: numpy.ndarray

all,I have a column in a dataframe that looks like this:allHoldingsFund[BrokerMixed] Out[419]: 78 ML 81 CITI 92 ML 173 CITI 235 ML 262 ML 264 ML 25617 …