Using a template twice on the same page

338 views
Skip to first unread message

Matt E

unread,
Apr 2, 2010, 1:36:37 PM4/2/10
to Django users
Is there a way to use a template twice on the same page? We don't want
to have to create a duplicate template just for a different variable.
Thanks for the help

orokusaki

unread,
Apr 2, 2010, 3:00:44 PM4/2/10
to Django users
Hey Matt,

If you're trying to use the same template twice in the same request,
you might want to reconsider a few things about the design, such as:
You may want to use an include instead, or you may want to use a loop
inside your template. Either way, here's one way to achieve that if
I'm simply misunderstanding your reasoning:


#views.py

from django.template.loader import render_to_string

def my_view(request):
"""
2 time template view which processes your template twice with
2
different contexts and returns the sum of both as one large
page
"""
first = render_to_string('/path/to/template.html', { 'foo':
'bar' })
second = render_to_string('/path/to/template.html', { 'spam':
'eggs' })

return first + second

Bill Freeman

unread,
Apr 2, 2010, 3:35:21 PM4/2/10
to django...@googlegroups.com
You can put a snippet in a separate template file and {% include %} it
twice from the
same pages specific template. I frequently do this in a for loop for rendering
more complex list items on more than one page, so I have one place to define
how a list item looks. But including it directly twice works as well.
I frequently do
that to render my next-previous page chooser both before and after a
list. The only
issue is that for it to render something different, it needs some different
variable in the context (for me, the loop variable), but you can set context
variables if need be. If it's to look the same both times (or you only need css
differences) then just include it twice.

> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
>

Reply all
Reply to author
Forward
0 new messages