views:

113

answers:

1

In one of my Django templates, I have a chunk of HTML which repeats at several places in the page. Is there a way I could use another template for this chunk alone and "instantiate" the template where required?

+3  A: 

You need to read about template inheritance.

Or you can use template composition.

Inheritance is, generally, a better way to go.

celopes
How will inheritance help me here? I am talking about chunks of HTML withing the same page... not across the site.
Vulcan Eager
Thanks. `include` looks promising. Is it possible to send a different variable/context to each `include` instance?
Vulcan Eager
@Agnel: Use composition then. In general though inheritance is a better mechanism for reusing template code and I thought a more generic answer would be useful to more people. Edited to imply that generally inheritance is a better way to go.
celopes
@Agnel: I don't think you can send different contexts to the same template. If you need to do that maybe you should render the section-template in the view multiple times and pass the rendered sections to the encompassing template in the context. You will need to look into how to compile a string into HTML (http://docs.djangoproject.com/en/dev/ref/templates/api/#compiling-a-string)
celopes
@celopes, I just looked at the manual. I think the `cycle` and `with` tags can be used to change context.
Vulcan Eager