How to use template within Django template?

1.2k views Asked by At

I have the django template like below:

<a href="https://example.com/url{{ mylist.0.id }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a>
<p>
{{ mylist.0.text|truncatewords:50 }}<br>
...

(the actual template is quite big)

It should be used 10 times on the same page, but 'external' html elements are different:

<div class="row">
  <div class="col-md-12 col-lg-12 block block-color-1">
    *django template here - mylist.0, truncatewords:50 *
  </div>
</div>

<div class="row">
  <div class="col-md-4 col-lg-4 block block-color-2">
    *django template here - mylist.1, truncatewords:15 *
  </div>
  <div class="col-md-8 col-lg-8 block block-color-3">
    *django template here - mylist.2, truncatewords:30 *
  </div>
</div>
...

Looks like even usage of for with considering first, last, odd and even elements will not simplify the task.

What can I do to have the template (given in the beginning) defined only once?

2

There are 2 answers

3
Wtower On BEST ANSWER

You can use the include tag in order to supply the included template with a consistent variable name:

For example:

parent.html

<div class="row">
    <div class="col-md-12 col-lg-12 block block-color-1">
        {% include 'templates/child.html' with list_item=mylist.0 t=50 only %}
    </div>
</div>

child.html

{{ list_item.text|truncatewords:t }}

UPDATE: As spectras recommended, you can use the with and only keywords within the tag in order to supply the included template with the necessary context.

0
Brandon Taylor On

You can use an include tag for that. It's part of the built-in tags: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#include

If you need to do something more complicated, you can always write your own template tags: https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/