I'm working on a project that takes in a markdown page and converts it into HTML before inserting it into the correct document. This is the code I'm running
Python
def markdown(request, entry):
pathOfFile = "entries/" + entry + ".md"
return render(request, "encyclopedia/entry.html", {
"html_markdown": markdown2.markdown_path(pathOfFile)
})
HTML
{% block body %}
<div>
{{ html_markdown }}
</div>
{% endblock %}
And this is what is returning on the web page
<h1>CSS</h1> <p>CSS is a language that can be used to add style to an HTML page.</p>
When I inspect the source of the page the HTML is encased in quotes. Is the problem that my html_markdown variable is being read as a string? What steps can I take to get the HTML to render properly? Thanks in advance for your help!
html_markdown will contain raw HTML, so if you render that in the template, it will escape characters like < to <, etc.
You can mark the string as "safe" with the |safe template filter [Django-doc] to prevent escaping these characters:
{% block body %}
<div>
{{ html_markdown|safe }}
</div>
{% endblock %}
Related
I'm experiencing a weird behavior with Jinja. I made a dynamic flask route and so I made a jinja modular template, it's just a for loop to create an element for each article present in some data (in a dict) I give to Jinja, the template looks like this :
{% for theme in article_data %}
{% for article in theme["article"] %}
{% if article["main"] == 1 %}
<div style="background-image: url('{{article['content']['image1']}}');" class="theme-item-bg frow space-between">
{% endif %}
{% endfor %}
<div class="wrapper-row space-between pinkfilter">
<div class="uB theme-item-text">{{theme["name"]}}</div>
<div class="pageChanger waves-effect waves-light btn uL primaryB" page="/nos-articles/{{theme['name']}}" title="{{theme['name']}}">Voir plus d'articles</div>
</div>
</div>
{% endfor %}
It does work correctly for most of my pages but for one, it have a really weird behavior, Jinja render one of the article correctly and nest the others in a strong element.
The data used to render the page have the same structure and is correctly parsed.
Is there a way to prevent Jinja from nesting stuff in a strongelement?
There must be either some html inside theme["name"] (fix it by escaping it with theme["name"]|escape), or a <strong> tag not closed in one your templates.
Jinja doesn’t insert random html tags, but the browsers do when trying to parse and fix a broken html code
Hi so I'm decrypting information so the value return is coming back as a byte. I'm trying to print it as a str so I can get rid of the b'' format. But I can't figure out how to do it in html template
{% for row in rows %}
{{ repr(password.decrypt(row['text']))[2:-1] }}
{% endfor %}
This is the code I tried, but I get repr not define. I'm trying to use python built in function repr in my html file
{% for row in rows %}
{{ password.decrypt(row['text'])[2:-1]|string }}
{% endfor %}
and pass the decrypt() function by retrun render_template("index.html", decrypt=decrypt) into your jinja template.
However, the jinja template will still go through your flask route to render as a real html before sending it to frontend. So I don't think there is difficulty in moving the function into py file.
I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template. The templating framework seems to escape the HTML automatically, so all <"'> characters are converted to HTML entities. How can I disable that so that the HTML renders correctly?
To turn off autoescaping when rendering a value, use the |safe filter.
{{ something|safe }}
Only do this on data you trust, since rendering untrusted data without escaping is a cross-site scripting vulnerability.
MarkupSafe provides Jinja's autoescaping behavior. You can import Markup and use it to declare a value HTML safe from the code:
from markupsafe import Markup
value = Markup('<strong>The HTML String</strong>')
Pass that to the templates and you don't have to use the |safe filter on it.
From the Jinja docs section HTML Escaping:
When automatic escaping is enabled everything is escaped by default
except for values explicitly marked as safe. Those can either be
marked by the application or in the template by using the |safe
filter.
Example:
<div class="info">
{{data.email_content|safe}}
</div>
When you have a lot of variables that don't need escaping, you can use an autoescape override block:
{% autoescape false %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}
For handling line-breaks specifically, I tried a number of options before finally settling for this:
{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split function) and also doesn't add an unnecesssary <br/> after the last item.
Some people seem to turn autoescape off which carries security risks to manipulate the string display.
If you only want to insert some linebreaks into a string and convert the linebreaks into <br />, then you could take a jinja macro like:
{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}
and in your template just call this with
{{ linebreaks_for_string( my_string_in_a_variable ) }}
Use the safe filter in your template, and then sanitize the HTML with the bleach library in your view. Using bleach, you can whitelist the HTML tags that you need to use.
This is the safest, as far as I know. I tried both the safe filter and the Markup class, and both ways allowed me to execute unwanted JavaScript. Not very safe!
In my django model I have to store html data as string like
item = RocketuItem(text=text, page_url=url, page_number=page_number, page_down=page_down)
and text =
<section> <h2>Object-oriented Python and Beginner Django</h2> <ul>
When i pull this in template i use ..
{% for page in pages %}
<div>{{ page.page_url|safe }}</div>>
<div>
{{ page.text|safe }}
I m using safe as it dosent display $lt etc [basically '<' gets converted to < if i dont use it]
This is wht i see at output on the page
<section> <h2>Object-oriented Python and Beginner Django</h2> <ul>
What i really want is for the code fro 'text' to be a part of the div so that it well get that formatting and show..
Object-oriented Python and Beginner Django
How do i do that ..
The safe filter should be enough to render the text as html in recent versions of Django. Try using:
{% autoescape off %} {{ content }} {% end autoescape %}
tags and see if that works for you.
Use this:
{% autoescape off %}{{ page.text }}{% endautoescape %}
Autoescape documentation
I have a about page in my python flask website. I want to write some text under a form definition. My python app has a definition for the about page.
class Aboutpageshow(flask.views.MethodView):
def get(self):
return flask.render_template('about.html')
and linking
app.add_url_rule('/about',view_func=Aboutpageshow.as_view('aboutpage'),
methods=["GET"])
And the html page definition is as follows
{% extends "base.html" %}
{% block content %}
<h1>About</h1>
<form method= action="{{url_for('aboutpage')}}">
<p> my text here </p>
</form>
</br>
{% endblock %}
{% block nav %}
<li>back</li>
{% endblock %}
In this process I want to write the text in this form space.
class wtforms.fields.Field
Stores and processes data, and generates HTML for a form field.
I am not sure if you are talking about placeholders or help text, so i will say for both.
The WtForms Form field takes description as one of the parameter
which will work as helptext for you when you render forms.
Refer : http://wtforms.simplecodes.com/docs/0.6.1/fields.html
In order to use placeholders with jinja2 templates, you have to use
something like this in your jinja2 templates
{{ demo.render(placeholder="abc")|safe }}