Search code examples
htmldjangounicodecharacter-encoding

Certain HTML entity codes not being evaluated


I have a view passing on information from a database:

def serve_article(request, id):
    served_article = Article.objects.get(pk=id)

    # Strips out new line and tab characters
    article_snippet = served_article.full_text.replace('\n','').replace('\t','')

    # Gets first 300 word characters
    article_snippet = re.match(r'(.{,300})\W', article_snippet).group(1)

    return render(request, 'article.html', {'served_article':served_article,
                                            'article_snippet':article_snippet})

article_snippet, a unicode string by the time it is rendered, contains many HTML entity codes (for example: ’ maps to ’ and © maps to © when rendered)

However, {{ article_snippet }} in the template does not evaluate these symbols, leaving them blank as if they were wrapped inside a <code> tag (they aren't).

I've got <meta charset="utf-8"> at the top, and other symbols on the page that are evaluating fine, so clearly these symbols are being escaped somehow. Why is this behavior happening, and how do I disable it?


Solution

  • To disable auto-escaping for an individual variable, use the safe filter:

    This will be escaped: {{ data }}
    This will not be escaped: {{ data|safe }}
    

    https://docs.djangoproject.com/en/dev/topics/templates/

    Ensure that your variable does not contain dangerous HTML provided by user (<script> tags etc.).