Knight Samar
Knight Samar

Reputation: 199

passing unicode strings from django to javascript

I have a bunch of unicode strings in my data which I need to pass from my django view to template for using in a JavaScript scriptlet that passes it to the web back and forth.

The problem is I want the strings to be represented in the JavaScript unicode form but I get strings with a u prefix from python.

For example, for the string mężczyźni, Python stores it as u'm\u0119\u017cczy\u017ani' but when it is passed to the template, it does not remove the u prefix which creates problems for JavaScript while processing it. I want it to be simply 'm\u0119\u017cczy\u017ani' so that the JavaScript code in the template can use it.

I tried using urqluote, smart_unicode, force_unicode but couldn't hit a solution or even a hack.

What do I do ?

Upvotes: 8

Views: 5413

Answers (1)

jpic
jpic

Reputation: 33420

Edit: Django 1.7+ no longer includes simplejson. Instead of

from django.utils import simplejson

write

import json

and then use json instead of simplejson.


You are probably printing the python repr of your data dict, and trying to parse it in javascript:

{{ your_python_data }}

Instead, you could export your data in json:

from django.utils import simplejson

json_data_string = simplejson.dumps(your_data)

And load the data directly in javascript:

var your_data = {{ json_data_string }};

You could also make a template filter:

from django.utils import simplejson
from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter
def as_json(data):
    return mark_safe(simplejson.dumps(data))

And in your template:

{% load your_template_tags %}

{{ your_python_data|as_json }}

Note that you should be careful with XSS, if some of "data" comes from user input, then you should sanitize it.

Upvotes: 12

Related Questions