What about putting it into <script type="application/json">?
On Thursday, April 9, 2015 at 8:50:50 PM UTC+3, Eric Plumb wrote:
>
> 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
>
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/443fa651-8378-4150-9e7c-1e467a2a1a68%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.