In my django project, I have a base.html from which all my templates {% extends 'base.html' %}. In that base template I want to do this to a list of all my algorithms.
{% for algorithm in algorithms %}
# list them out as links in nav bar
{% endfor %}
But I'm not passing algorithms to the base since it's just extending other templates.
I don't know how to solve this. My thought was to use {% load %} in the base template which would basically.
from algorithms.models import Algorithm
from django import template
register = template.Library()
def GetAlgorithmObjects():
a = Algorithm.objects.all()
return {'algorithms': a}
I'm not sure of how load works which would explain this failure. How would you actually implement this or should I go a different path.
You can make it with inclusion tag https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
In your app algorithms create directory templatetags and put a file in it named algorithms_tags.py (of course in this directory there must be a file named __init__.py)
Then the content of the file is similar to what you wrote:
from algorithms.models import Algorithm
from django import template
register = template.Library()
@register.inclusion_tag('algorithms/show_algorithms.html')
def show_algorithms():
a = Algorithm.objects.all()
return {'algorithms': a}
Then you need a template located at algorithms/templates/algorithms/show_algorithms.html with the following content:
{% for algorithm in algorithms %}
# list them out as links in nav bar
{% endfor %}
You can use it in your base.html as follows:
{% load algorithms_tags %}
{% show_algorithms %}
Some explanations:
{% load algorithms_tags %} "algorithms_tags" is the name of the .py file created in the templatetags directory (without the extension){% show_algorithms %} "show_algorithms" is the name of the function decorated with register.inclusion_tag in inclusion_tag.pyIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With