Milano Slesarik Milano Slesarik - 1 month ago 8
HTML Question

How to inject Django template code into template through {{ variable/method }}?

I have a model Reservation which I use in many templates. It's handy to create it's own

HTML/Django
snippet which is being injected into the template through variable/model method.

The raw
HTML
is correct using the method but Django template language isn't interpreted correctly.

This is a Reservation method:

def get_html_description(self):
return """<ul>
<li><b>ID:</b> {{ reservation.id }}</li>
<hr>
<li><b>From:</b> {{ reservation.get_text_destination_from }}</li>
<li><b>To:</b> {{ reservation.get_text_destination_to }}</li>
<hr>
<li><b>Date:</b> {{ reservation.get_date }}</li>
<li><b>Time:</b> {{ reservation.get_time }}</li>
</ul>"""


Now I'm trying to inject this code into the template:

<div class="events">
{% for reservation in data.1 %}
<div class="event">
<h4>{{ reservation.get_text_destination_from }} to {{ reservation.get_text_destination_to }}</h4>
<div class="desc">
{% autoescape off %}{{ reservation.get_html_description }}{% endautoescape %}
</div>...
...


Unfortunately it renders something like this:

enter image description here

Do you know what to do? I've already tried filter
|safe
and
{% autoescape off %}

Answer

What you are asking for is double substitution and I don't think the Django templating engine will do that. Since you are pulling the data from a Reservation instance, I would just fill it in using string substitution. For example:

 return """<ul>
                <li><b>ID:</b> {pk}</li>
                <hr>
                <li><b>From:</b> {destination_from}</li>
                ...
           </ul>""".format(pk=self.id,
                           destination_from=self.reservation.get_text_destination_from)
Comments