Stefan Musarra
Stefan Musarra

Reputation: 1501

Django Templates: How to display html code?

I'm trying to display some HTML markup in a blog, and would like to know if there is a way to wrap a section of my Django template directly, without putting it into a context variable.

For example, I would like to output a bunch of code, some of it JavaScript, and some of it HTML, and some of it CSS. If I enter in the code directly into my Django template, and wrap it in some pre tags:

<pre>
  /* Here is the markup I want to display: */
   ... lots of HTML
</pre>

the HTML tags are rendered.

Of course, to display:

<

I should use

&lt;

and to display

>

I should use

&gt; 

I tried adding the Django tag {% autoescape on %} around the code section, but it had no effect because I'm not rendering a context variable.

I would like to know if there is an easier way than replacing every occurrence of < with &lt; and every occurrence of > with &gt;

I also know that if I put the code that I want to display into a context variable, then in my template, just displaying that context variable would automatically escape the code.

But I would rather just be able to directly cut and paste the code I want to display into my template. Is there a way to do this and display the HTML tags (i.e.

<h1> Heading Level 1 </h1>

without writing it in my template as:

&lt;h1&gt; Heading Level 1 &lt;/h1&gt;

Upvotes: 2

Views: 5826

Answers (3)

Smit Patel
Smit Patel

Reputation: 63

NOTE: Before you try to implement manually, please have a look at ckeditor. ckeditor documentation if this is not what you are looking for, then only proceed with answer.


Just Wrap your variable inside following Django template tag.

{% autoescape off %}
    {{your_variable_here}}
{% endautoescape %}

put HTML code in "your_variable_here" variable And Django Will Display It as HTML. All HTML Tags will Work.

EDIT: Sorry, I missed important part to mention. in views do this

from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})

and pass this rendered string to template variable and render the given template inside other template by putting lines

{% autoescape off %}
    {{rendered}}
{% endautoescape %}

Upvotes: 2

Le Minaw
Le Minaw

Reputation: 885

This question is old, but it pops on search engines and no answer is correct imo.

Sławek Kabik's is deprecated, Smit Patel's is overly complicated (it bloats views).

In order to do what OP asked for, you have to use the force_escape built-in filter in a {% filter %} tag.

Example:

<pre>
  <code>
    {% filter force_escape %}
      <span class="hello">Anything HTML really</span>
    {% endfilter %}
  </code>
</pre>

Output:

<pre>
  <code>
    &lt;span class=&quot;hello&quot;&gt;Anything HTML really&lt;/span&gt;
  </code>
</pre>

Upvotes: 2

Sławek Kabik
Sławek Kabik

Reputation: 699

You have to use xmp tags.

<xmp>
    <h1>Testing Html</h1> 
</xmp>

Upvotes: 2

Related Questions