Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape problem in django templates

Let's say that I have this string:

s = '<p>Hello!</p>'

When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:

{{s|safe}}

or disable autoescape:

{%autoescape off}
{{s}}
{%endautoescape%}

or inside the python code declare it safe:

from django.utils.safestring import mark_safe
s = mark_safe(s)

None of these options are working for me. Whatever I do, the string is displayed as:

<p>Hello!</p>

I must be missing something, just couldn't figure out what. Is there some security setting somewhere that disallows escaping?

EDIT: Bizarre, the problem seems to be gone after I have restarted the computer.

like image 991
shanyu Avatar asked May 15 '09 22:05

shanyu


People also ask

How do I escape a Django template?

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.

Does prettier work with Django?

This feature is no longer supported. Instead, configure VS Code default formatters or use . prettierignore. This tells VS Code to not run automatic formatting when saving django-html files.

What is {% block %} in Django?

The concept of { % block %} is template inheritance which allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. 3 ) Now suppose all of your 3 templates also having same HTML div which defines some popular posts.


2 Answers

I think you should write as follows

{{s|escape|safe}}

it is ok for me

like image 117
Kevin Avatar answered Sep 20 '22 15:09

Kevin


You pretty much covered it, those are indeed all the ways to disable autoescaping.

Are you sure the value you are talking about is actually s = '<p>Hello!</p>'?

My hunch is that you have additional escaping somewhere in that string...

like image 43
Yuval Adam Avatar answered Sep 21 '22 15:09

Yuval Adam