Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for dynamic navigation in django?

Tags:

django

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.

like image 354
meder omuraliev Avatar asked Jan 22 '23 13:01

meder omuraliev


1 Answers

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 %}
like image 138
Steve Jalim Avatar answered Jan 31 '23 04:01

Steve Jalim