Question

I was wondering if there is a way of including a variable in an include statement in a Django template. For example if you have a for loop over a set of objects and you want to load only templates related to those objects (example bellow).

{% for app in apps %}
<div class="modal fade hidden" id="myModal_{{ app.id }}">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Add {{ app.title }}</h3>
  </div>
  <div class="modal-body">
    <form class="bs-docs-example form-horizontal">


      {% include "app_templates/{{ app.title }}/modal-config.html" %}


    </form>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="add-app-btn btn btn-primary" data-appid="{{ app.id }}">Add</button>
  </div>
</div>
{% endfor %}

Or is there a better way of doing this. Thanks.

Was it helpful?

Solution

You can do it like this:

{% with template_name="app_templates/"|add:app.title|add:"/modal-config.html" %}
    {% include template_name %}
{% endwith %}

I'm not sure maybe this would even work:

{% include "app_templates/"|add:app.title|add:"/modal-config.html" %}.

But in that case I'd rather make a template tag or filter to encapsulate this logic away from the template.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top