Newbie: How to implement a app/module, which I can include from my html?

47 views
Skip to first unread message

ThomasTheDjangoFan

unread,
Nov 27, 2014, 3:54:36 AM11/27/14
to django...@googlegroups.com
Hi guys,

I want to display a block of category-links in various places of the website. Those links are populated by making a Category.objects.all request in a view. So right now it seems like each view that should contain those links needs to put the "Category" Model in its context.

Now I would be really thankful for a tip on how to NOT repeat myself (DRY):
Is there a way to "{% include 'category-links.html' %}" and have the .html get its content from a specific view?

Kind regards
Thomas

James Bennett

unread,
Nov 27, 2014, 3:55:50 AM11/27/14
to django...@googlegroups.com
The usual way would be to write a custom template tag that fetches the objects and puts them into the template context.

ThomasTheDjangoFan

unread,
Nov 27, 2014, 4:04:00 AM11/27/14
to django...@googlegroups.com
Oh ok.

so it would be something like:

in home.html
{% include 'category-list.html' %}

in category-lists.html
{% load those_categories %}
<!-- display the categories as html -->

?

Mario Gudelj

unread,
Nov 27, 2014, 5:19:20 AM11/27/14
to django...@googlegroups.com

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags here you go chief

--
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 post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d88ef650-0d18-4d6d-bad9-8a6a990524bf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Collin Anderson

unread,
Nov 30, 2014, 1:18:19 PM11/30/14
to django...@googlegroups.com
Assignment tags are my favorite.

@register.assignment_tag
def get_categories():
   
return Category.objects.all()

{% get_categories as categories %}
{% for category in categories %}
{{ category }}
{% endfor %}

Collin
Reply all
Reply to author
Forward
0 new messages