Hi Djangoers!
Sometimes in the course of human events it becomes necessary to encode a JSON object directly into a template. We all prefer AJAX and REST APIs and the rest of the TOFLAs, but in the cases where it has to be part of the template, I'm wondering if there's an accepted canonical best-practice way to do so and remain safe from XSS attacks and other nastiness.
I'm aware of the following two methods:
1. HTML attribute loaded by jQuery's $.data()
# view
return { ... {'my_obj': mark_safe(escape(json.dumps(obj))) } ... }
# template
<div data-my-object={{ my_obj }}>...</div>
# JS
var myObj = $('div').data('my-object'); // implicitly calls JSON.parse() on the encoded object
2. Explicitly parsed JS object
# view
return { ... {'my_obj': mark_safe(escapejs(json.dumps(obj))) } ... }
# template
<script>
var myObj = JSON.parse('{{ my_obj }}')
</script>
Are there better methods? It seems like this ought to come up often in building safe websites, but I don't see a consensus out there on the Web. Thanks in advance for your consideration!
Eric