Can I use the Django templating language to build HTML for use in a JSON response field?
I have a scenario where I would like to return JSON from my view, which is usually pretty straight forward, but I need one of the HTML attributes, preferably built in the Django templating language, so I can take advantage of filters and other out-of-the-box functionality.
Is there a way to intercept a string generated by the Django templating engine and then access it in a view so that it can be wrapped in a JSON envelope attribute?
+3
source to share
1 answer
There is no need to "intercept" anything. The Django templates provided are just strings, and a handy shortcut to do exactly what you want:
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
+4
source to share