My primary navigation consists of news categories, which belong to the Category model. I hardcoded the nav in templates/base.开发者_运维知识库html
but want to make it dynamic...
Is it a bad idea to embed model code in my template? If so how should I pull them? Should I make the nav file separate? And not only will I just rely on the categories, but I also will need a 'home' link, and some other links as well.
If possible it would be great if I could make a new Navigation model but I'm not sure how I would be able to include news categories from the category table so they could also be items in the nav.
Why not create in inclusion tag where you shepherd together all your relevant categories data/links, make them into a list, then pass that to the inclusion tag's mini template to be rendered in whatever page you wish?
eg, something like this (bearing in mind I have no idea what your current page/content looks like)
@register.inclusion_tag('/path/to/templates/my_nav_inclusion_tag.html')
def my_nav_inclusion_tag()
#create your base link and add it to the list of links
links = [['Home', '/']]
for all the categories you want to add:
# (It's up to you to decide how to wrangle your categories into shape)
links.append([category_name, category_url])
return {'links':links}
In the inclusion tag template (my_nav_inclusion_tag.html), try something like:
{% for link in links %}
<a href="{{link.1}}">{{link.0}}</a>
{% endfor %}
And in whatever templates you need to show the nav in, simply call the inclusion tag, eg:
{% my_nav_inclusion_tag %}
To answer your question, yes it's bad to embed model code in your template. The django way of making your pre-processed navigation information available to every template (including base.html
) is via a RequestContext.
http://docs.djangoproject.com/en/1.1/ref/templates/api/#id1
http://docs.djangoproject.com/en/1.1/ref/settings/#setting-TEMPLATE_CONTEXT_PROCESSORS
精彩评论