Using non-ascii in Django templates

Ask the readers

Using non-ascii in Django templates

I hope some reader can help me uit here…

We were trying to use non Ascii characters (like ♥ for example) in the Django templates, but couldn’t get it to work.

We worked around this by using a template variable ( {{ nonAsciiHeart }} for example) and then put the following in the view:

nonAsciiHeart = '\xe2\x99\xa5'
return render('example_template.html', {'nonAsciiHeart': nonAsciiHeart})

There must be a better way to do this. Does anyone know how? Please share it in the comments!

Discussion

One comment for “Using non-ascii in Django templates”

  1. Assuming you’re using Django 1.0 or later (well, anything since the unicode merge landed in Django, which was just after 0.96), you can use non-ASCII characters in templates. It would be a bit short-sighted if we supported non-ASCII everywhere except in templates!

    You must be doing something a bit unusual here. The most likely thing I can think of is your files aren’t saved as UTF-8. Django assumes the template files are in UTF-8 (it has to assume something, since auto-character set detection is unreliable in many cases) and if you have saved the files in some other encoding, you’ll need to set the FILE_CHARSET setting appropriately. Have a look at the ref/unicode.txt documentation file for information.

    I just rechecked this with the exact example you’re using and it loads from a template file and renders without problems.

    Posted by Malcolm Tredinnick | November 28, 2008, 6:16 am

Post a comment

Categories

  • No categories

Django Hosting:

DjangoDays recommends the following Django hosting provider: