[Django]-Django 1.9.3 – How to pass HTML template to index template

4👍

The problem is that this code:

def getDetails(request):
  var = "{% if 10 > 5 %}<h1>TRUE</h1>{% endif %}"
  return HttpResponse(
    json.dumps(var),
    content_type="application/json"
  )

literally just puts that template code into a string and sends it as a JSON object. At no point does the template code get converted to a HTML string.

From your comments, you imply that the server doesn’t interpret template code, but this isn’t correct! Django’s default views most certainly do get involved.

You can do this interpretation yourself using the Template class.

Try the following code:

from django.template import Context, Template
template = Template("{% if 10 > 5 %}<h1>{{ value }}</h1>{% endif %}")

def getDetails(request):
  context = Context({"value": "TRUE"})
  output = template.render(context)
  return HttpResponse(
    json.dumps(output),
    content_type="application/json"
  )

The above example, adapted from the Django 1.9 documentation, demonstrates programmatically using a Template, as well as supplying additional information using a Context object.


Perhaps a better alternative is to leave your template code in a partial template file somewhere. For example, let’s say you’ve created table.html containing the following template code:

<table>
{% for item in items %}
  <tr><td>{{ item }}</td></tr>
{% endfor %}
</table>

Then you can load and render it as follows:

from django.template.loader import render_to_string

def getDetails(request):
  table_rows = ['item 1', 'item 2', 'item 3']
  output = render_to_string("table.html", {"items": table_rows})
  return HttpResponse(
    json.dumps(output),
    content_type="application/json"
  )

This invocation of render_to_string will load template code from table.html, and dynamically create a context using the supplied dict. In this case, the items entry in the Context is set to an array so that the {% for %} tag can loop through it.

👤kibibu

Leave a comment