The solution lies in the Jinja Template and not in Python itself.
Hence we can use this in both Flask and Django.

Let’s say this is my Python code along with the HTML part given below.



The variable “post” holds the value of a string having some HTML code. I have used the render_template() function to pass this variable in an HTML template having the structure shown in the above Gist. The div with the class name “blog” shows the required content.

The solution is using the bitwise OR operator followed by the keyword “safe”.
{{ my_string | safe }}
This syntax of Jinja Template will take care of the HTML tags that are there in the string.

The “| safe” used is called a filter from Jinja2. To know more about filters, follow the link: Jinja2 Filters

Fun Fact:

I searched a lot on this topic for about three days and the solution I got was a one-liner, in fact, a single operator!

I was developing a blogging website in Python Flask and my blog was stored as a string of HTML code in the database. Whenever I tried to display the blog, it would show me the HTML code. After Googling about a day, I was gonna quit my whole project, because I found absolutely nothing! The second day, I used other search engines to check different search results and to my hand, I got failure again. On the third day, I was literally skipping through the whole course on different channels over YouTube to find the solution for this haphazard.

I finally got it!
Ironically, in a Django tutorial!


If you found this blog helpful, please leave the reviews in the contact section.