integrate html into django template - python

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 &lt 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

Related

Flask's Jinja nesting some rendered elements in 'strong' elements

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

How to ignore special character in argument of render_template in Flask and HTML [duplicate]

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!

How do you declare python variables within flask templates?

I've got some basic experience building websites using a LAMP stack. I've also got some experience with data processing using Python. I'm trying to get a grip on the mongodb-flask-python thing, so I fired everything up using this boilerplate: https://github.com/hansonkd/FlaskBootstrapSecurity
All is well.
To experiment, I tried declaring a variable and printing it...
I get this error message:
TemplateSyntaxError: Encountered unknown tag 'x'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
Here's my main index.html page
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12">
Hello World, at {{ now }}, {{ now|time_ago }}
</div>
</div>
<div class="row-center">
<div class="col">
{% x = [0,1,2,3,4,5] %}
{% for number in x}
<li> {% print(number) %}
{% endfor %}
</div>
</div>
{% endblock %}
I love learning new things, but man, can I ever get hung up for hours on the simplest of things... any help would be greatly appreciated!!!
Flask uses Jinja as its default templating engine.
The templating language is python-esque, but is not python. This is different from something like a phtml file, which is php interspersed with html.
Check the jinja documentation for more of what you can do, but here's how you set a variable within a template:
{% set x = [0,1,2,3,4,5] %}
http://jinja.pocoo.org/docs/2.9/templates/#assignments
Try this:
{% set x = [0,1,2,3,4,5] %}
See Jinja docs.

using angular expressions in a django based webapp

I recently started with django and I have experience with angularJS. I got pretty confused by the static media rendering of Django which uses the same moustache ({{ }}) as angular. So how to use angular expressions while working with django..
<body>
<h1>Including Static Media</h1>
<img src="{% static "rango.jpg" %}" alt="Picture of Rango" /> <!-- Images -->
</body>
Instead of using the rendering as it is, can i use something like
image src="/static/images/xyz.jpg"
However if I want to load my images or js script dynamically or if I have to make URL's dynamically using something like ng-href="#!/{{redirectService(parameters)}}". It seems that syntax of both frameworks conflict alot. Can anyone help me regarding this.?
Check out the {% verbatim %} tag and/or the {% templatetag %} tag.
From the docs:
verbatim
Stops the template engine from rendering the contents of this block
tag.
A common use is to allow a JavaScript template layer that collides
with Django’s syntax. For example:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
You can also designate a specific closing tag, allowing the use of {% endverbatim %} as part of the unrendered contents:
{% verbatim myblock %}
Avoid template rendering via the {% verbatim %}{% end verbatim %} block.
{% endverbatim myblock %}
templatetag
Outputs one of the syntax characters used to compose template tags.
Since the template system has no concept of “escaping”, to display one
of the bits used in template tags, you must use the {% templatetag %}
tag.
The argument tells which template bit to output:
Argument | Outputs
————————————————|————————
openblock | {%
closeblock | %}
openvariable | {{
closevariable | }}
openbrace | {
closebrace | }
opencomment | {#
closecomment | #}
Sample usage:
{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}

Django unable to understand template html format

I am learning Django framework, I setup Django on my local host and successfully run my first app, and i downloaded some web app from git and then i tried to understand it but when i opened template html the format used their was completly different from original html format, so i just want to know what scripting, or language they are using to build html files, Here is a sample code
{% extends "admin/change_list.html" %}
{% load i18n %}
{% block object-tools-items %}
{% if not is_popup %}
<a href="{{ recoverlist_url }}" class="recoverlink btn">
<i class="icon-repeat"></i>
{% blocktrans with cl.opts.verbose_name_plural|escape as name %}Recover deleted {{ name }}{% endblocktrans %}</a>
{% endif %}
{{block.super}}
{% endblock %}
I am unable to get what {% %} doing here, Is it a scripting tag just like jsp or something else, If it is a scripting that what kind of script is it ? because normally html files starts with
<head>
tag.
Is it a scripting tag just like jsp or something else
Yes.
If it is a scripting that what kind of script is it ?
Django Template language
because normally html files starts with <head> tag.
It's not HTML. It's a template language that render and outputs HTML.
I'd suggest you go through the Django tutorial.

Categories