0

I have some partial templates which I load in on various pages and sometimes the inclusion of these partials is dynamic, these have their own related models.

At present I am passing models via views to the main page, but is there not a way to load data for these partials independant of the parent page and view?

Just seems like I am duplicating code in the views which cant be right!

Can I not create a custom tag or something which would allow me to load data into the partial irrespective of the data passed in the parent page and its view?

A good example of this is a partial for "latest posts" which exists in a sidebar partial and loads on many different parent templates

Cheers Kevin

KevTuck
  • 113
  • 8

1 Answers1

1

A custom template tag can do this for you. You could write an inclusion tag, which will output the rendered template directly:

# yourapp/templatetags/appname_tags.py

def latest_posts(num_posts):
    posts = Post.objects.all()[:num_posts]
    return {'posts': posts}
register.inclusion_tag('yourapp/partials/latest_posts.html')(latest_posts)
Chris Lawlor
  • 47,306
  • 11
  • 48
  • 68
  • I have completed whats been listed, added a related directory structure and __init__.py files and also checked Installed_Apps and amended. However it seems I can load the template tag library without error {% load component_tags %} but when I go to use a tag {% nav_categories %} I just keep getting an error for "Invalid Block Tag: nav_categories" – KevTuck Sep 14 '12 at 14:05
  • are you sure you registered the tag? – Chris Lawlor Sep 14 '12 at 17:33
  • Ignore me, I had the register stuff in the wrong place with respect to sequence. ;-) – KevTuck Sep 14 '12 at 18:49