Dynamic navigation recommendations in django?

My main navigation consists of news categories that belong to the category model. I hard coded nav into templates/base.html, but want to make it dynamic ...

Is it nice to embed model code in my template? If so, how do I pull them? Should I make the nav file separately? And not only will I just rely on categories, but I will also need the "home" link and some other links.

If possible, it would be great if I could create a new navigation model, but I'm not sure how I can include news categories from the category table so that they can also be elements in the navigator.

+3
source share
2 answers

, /, , - , , ?

, - ( , , /)

@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 up to you to decide how to wrangle your categories into shape)
    links.append([category_name, category_url])

  return {'links':links}

(my_nav_inclusion_tag.html) - :

{% for link in links %}
   <a href="{{link.1}}">{{link.0}}</a> 
{% endfor %}

, , , :

{% my_nav_inclusion_tag %}
+6

Source: https://habr.com/ru/post/1732645/


All Articles