1

I need to pass some data to javascript. So I've created a template tag:

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

register = template.Library()

@register.simple_tag
def mydata():
    return mark_safe(json.dumps([("a", 1), ("b", 2)])

Then in my template,

<div id="mydata" data-stuff="{% mydata %}" style="display:none;"></div>

Which is used in a js file with jquery loaded:

$('#mydata').data('stuff') //automatically does JSON.parse

The problem is the quotes from "a" and "b" break the HTML attribute syntax. I can simply change to single quotes (data-stuff='{% mydata %}') but is there a more definitive django approach to injecting JSON into the template? Perhaps something like an escape_my_json or escape_for_html_attribute function.

1 Answer 1

2

Despite the fact it is a bit hacky to store json in attribute, single-quotation (apostrophe , U+0027) is not a valid string delimiter in JSON. Some browsers may have problems with this, although I cannot point out any.

If the JSON struct is not complex store every field as a separate data-*, otherwise in JS.

If you need to use attribute... really, really ...I would not replace quotes (simple replace will be loosy) more likely encode it with base64.

Note about escaping: To escape double-quotes (single as well) you can use filter addslashes (or in python django.template.defaultfilters.addslashes), but it is not json data aware so it may break.

Sign up to request clarification or add additional context in comments.

2 Comments

OK, so you recommend <script>var mydata = JSON.parse('{% mydata %}');</script>? I'm surprised that jquery explicitly tried to parse data- attributes as JSON if it's considered so hacky. Also I meant use single quotes for the attribute rather than within the JSON.
even without JSON.parse since JSON object is valid JS object var mydata = {% mydata %};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.