views:

266

answers:

2

Is there possibility to narrow context for include.

For example, I have "for" tag that gets from posts array - one post. Than I wonna put this post inside "include" tag to render in more detail context. Is there custom tags for this?

A: 

Using the {% include 'foo.html' %} tag gives the foo.html template access to the complete context of the template that is including it. I'm not sure why you would need to limit the context for the included template.

If limiting the context is truly a need, then I'd suggest looking at writing a custom template tag that performs your include but renders the included template with a specified context. That is relatively trivial to do, but, again, it sounds like there may be a better way to approach this problem.

You can find info about writing custom template tags on the DjangoProject.com site (this page).

shawnr
While true, this has the unnecessary restriction that the variables in question need to be 1) pre-computed in the view, and 2) the same for every time the inclusion takes place. With an inclusion tag, the template designer has control over both these factors. They are both viable options, but I personally consider the {% include %} to be the one that's more limiting.
Cide
Good point. Your final answer about the inclusion tag is definitely better than mine, and point well taken.
shawnr
+6  A: 

While I'm having some problem interpreting your question, I believe what you're looking for is what django calls an "inclusion tag". They are quite simple to write:

>>> from django import template
>>> register = template.Library()
>>> @register.inclusion_tag('my_template.html')
>>> def my_tag(post):
>>>     return {'post': post}

This should go inside a python module named "templatetags" inside one of your apps (don't forget __init__.py!). Then, you can load it (if you named your file my_tag.py), as so: {% load my_tag %}. Whenever you use {% my_tag post %} after that point, Django will automatically include and render the template my_template.html, with the context specified by the tag's return value. For more information, see Django's custom template tags.

Cide