Simon Willison wrote:
> 
> 
> On 14 Nov 2005, at 06:06, Tom Tobin wrote:
> 
>> A bit stumped here . . .  Is there a recommended convention for
>> repeating blocks within a template?  e.g., I have a paginated
>> object_list generic view, and I want to repeat my pager code (i.e.,
>> "back", "next") at both the top and bottom of the list without copying
>> and pasting.
> 
> 
> Not really. You can write a custom template tag for your buttons but 
> that might be considered overkill - and would also mean that some of 
> your presentation logic would end up in Python code (in the template 
> tag definition).
> 
> Maybe it's time we bit the bullet and introduced a {% capture %} tag 
> (or similar) that chucks the rendered output of its contents in a 
> variable in the context. Then you could do this:
> 
> {% capture pagination_controls %}
> ... HTML goes here ...
> {% end capture %}
> {{ pagination_controls }}
> 
> ... more stuff ...
> 
> {{ pagination_controls }}
> 
> I think we've avoided this in the past because it makes Django's 
> template language too much like a programming language, but I think  it
> provides an elegant solution to your problem and hence should be a 
> candidate for inclusion - unless we can come up with a more elegant 
> solution.
> 
> Cheers,
> 
> Simon Willison
> 

For this kind of thing I use @inclusion_tag. This is in new-admin and
ticket #625 . It is a decorator which makes creating simple tags very easy:

--------------------
tag definition
----------------------
@inclusion_tag('farming/cow_detail')
def cow_display(cow):
    return {
       'name': cow.name,
       'similar': find_similar_cows(cow)
    }
-------------------------
template : 'farming/cow_detail'
-------------------------
<div>
<h2>{{name}}</h2>
<b> similar cows: </b>
{%for cow in similar %}
   <p>{{cow.name}}</p>
{% end for %}
</div>
--------------------------
Use in other template
-------------------------
{% cow_display cow %}
------------------------

The good thing about defining a template tag is that it is easily
reusable across multiple templates, not just within one. For even
simpler cases, I use the {% include path/to/template %} tag detailed in
#598.

Reply via email to