Dmitry Torba Dmitry Torba - 8 months ago 29
Python Question

Including the same blocks in several pages in Django

On my website, blog posts appear in multiple places across the site. I want to create a template like

that given the list of blog posts (as an argument to
) creates the block with these posts, formatted and processed.

There are several disconnected pages to which I want to display
. Thus, I can not say that
extend any of them. I wonder if there is a way to insert whatever template processed to arbitrary page? If yes, how to I pass variables (which may be instances of the classes) to the blog_posts template?


You can either render blog_posts.html to string and pass it as a variable to the other template:

from django.template.loader import get_template
blog_posts = get_template('/path/to/blog_posts.htm')
somevar = blog_posts.render({'foo': 'foo', 'bar': 'baz'})

then place {{ somevar }} in the other template - or just {% include '/path/to/blog_posts.html' %} in the other; the included template will have access to all variables passed to the 'parent' one.