Reputation: 1316
I have a simple (relatively) model such as:
models.py
class Author( models.Model ):
first_name = model.CharField( max_length=30 );
last_name = model.CharField( max_length=30 );
something = model.FloatField( );
class Book( models.Model ):
name = model.CharField( max_length=200 );
authors = model.ManyToManyField( Author );
template/book.html
{% for book in books %}
{{ book.name }}
<div id="authors">
{% for author in book.authors.all %}
{{ author|template:"author_short.html" }} *** unsure here
{% endfor %}
</div>
{% endfor %}
author_short.html (for example...)
<div style="border: 1px solid #f00;">
Name: {{ first_name }} {{ last_name }}
</div>
What I would like to be able to do is to format the authors' information in the inner loop based on some template. It seems like I should be able to do that type of thing.
In the end what I want to do is to be able to add an author (in the same format!) using an ajax call. I know I can add via ajax, but I would have to have the formatting definition in two places, and therefore not that DRY (unless I am missing another way of doing this, which is quite possible).
Upvotes: 0
Views: 27
Reputation: 99660
You can use the include
templatetag for this.
Loads a template and renders it with the current context. This is a way of “including” other templates within a template
{% for author in book.authors.all %}
{% include "author_short.html" %}
{% endfor %}
and author_short.html
can still be:
<div style="border: 1px solid #f00;">
Name: {{ first_name }} {{ last_name }}
</div>
which can be reused
Upvotes: 1