Tyler
Tyler

Reputation: 2957

Simple Django question: how to allow html as output from a variable?

this template variable {{object.video.description}} is outputing this text:

Welcome to <a href="http://google.com">Saint Francis Academy</a> in the heart of Washington.

How can I get the link to show as an actual link instead of being replaced with html entities. I tried filtering it as safe but no luck: {{object.video.description|safe}}

Upvotes: 1

Views: 1328

Answers (2)

dr jimbob
dr jimbob

Reputation: 17751

Can you go to the django shell and see what text is recorded in object.video.description?

How/where does video.description get defined as an html string (what I'm guessing is that a < is already be escaped into &lt; at that point and hence safe won't help). Marking as safe prevents django from converting < to &lt; right before rendering in the template; but won't convert a string containing &lt; into a <.

If the string is originally saved with &lt;s and &gts you can convert them to < and > by a simple python replacement somewhere in your string processing. E.g., in your view do something like:

htmlCodes = (('&', '&amp;'),
             ('<', '&lt;'),
             ('>', '&gt;'),
             ('"', '&quot;'),
             ("'", '&#39;'),)

def unescape(some_html_str):
    for c, html_code in htmlCodes:
        some_html_str = some_html_str.replace(html_code, c)
    return some_html_str

and then remember to unescape your string in your view before putting it in the context (and still remember to mark it safe). See How do I perform HTML decoding/encoding using Python/Django?

Also it may be better/easier for you to use mark_safe (from django.utils.safestring import mark_safe) in your views to make sure only safe strings are marked safe rather than have your template always render something safe.

Upvotes: 3

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

{% load markup %}
{{ object.video.description|markdown }}

Upvotes: 1

Related Questions