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.