Template inheritance with dynamic content

31 views
Skip to first unread message

Tristania W

unread,
Nov 13, 2020, 9:31:25 AM11/13/20
to Django users
Is it possible to make one sub-template inherit a div with dynamic content from an upper level template?

For eg., Template2 extends Template1. Within Template1, there is a div XXX that depends on a variable {{ var1 }}. This variable is passed to the view def view1, which renders Template 1. When Template2 is rendered, this div XXX is not rendered, because of the dynamic content.

Is there a DRY (Don't Repeat Yourself) way to make this inheritance possible? 

Thanks.

David Nugent

unread,
Nov 14, 2020, 1:22:13 AM11/14/20
to django...@googlegroups.com
You can achieve what you are looking for using the include directive.

Just have your parent and child include the same block and use with… phrase to override variables within the included template.

Regards,
David


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/497e48c4-3bd8-4f14-84df-b70146712e77n%40googlegroups.com.

Tristania W

unread,
Nov 14, 2020, 6:04:04 AM11/14/20
to Django users
Hi,

To follow up, when I tried the following:
 {% include "child_template.html" with zip_list=zip_list%}
if the variable zip_list is a zip object, defined as following in the view,
   zip_list= zip (list1, list2, list3)
the "include" does not work. But if I pass any other normal variable (such as a simple list, or numeric or string), the "include" tag works fine.

How do I pass a zip object into this tag?

Thanks,

Tristania W

unread,
Nov 16, 2020, 4:10:28 AM11/16/20
to Django users
Thanks, David, for answering the following-up question.

I have figured out the problem. The "zip" object works with "include" as you have anticipated.

The issue that I found is that, in my view, I am zipping the lists in a different function (called "def give_me_zip"). This function returns the zip object. In my view (say "def some_view"), when I call this function, (say "zip_list = give_me_zip(list1, list2, list3)" ), if I pass this "zip_list" to "include", nothing is rendered.

But, if I do the zipping within "some_view" itself, then passing the zip object into "include" works.

I have no idea why, though.

Thanks very much.

Reply all
Reply to author
Forward
0 new messages