在我的django项目中,我有一个base.html,我的所有模板都从{.extended'base.html'%}扩展。在该基本模板中,我想对所有算法列表进行此操作。
{% for algorithm in algorithms %}
# list them out as links in nav bar
{% endfor %}
但是我没有将算法传递给基础,因为它只是扩展了其他模板。
我不知道该怎么解决。我的想法是在基本模板中使用{%load%},基本上。
from algorithms.models import Algorithm
from django import template
register = template.Library()
def GetAlgorithmObjects():
a = Algorithm.objects.all()
return {'algorithms': a}
我不确定负载如何工作,这可以解释这种故障。您实际上将如何实现这一目标,或者我应该走另外一条路。
您可以使用包含标签https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
在您的应用程序的algorithms
create目录中,templatetags
并放置一个名为的文件algorithms_tags.py
(当然,在此目录中必须有一个名为的文件__init__.py
)
然后文件的内容类似于您编写的内容:
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}
然后,您需要一个模板,algorithms/templates/algorithms/show_algorithms.html
其中包含以下内容:
{% for algorithm in algorithms %}
# list them out as links in nav bar
{% endfor %}
您可以base.html
按以下方式使用它:
{% load algorithms_tags %}
{% show_algorithms %}
一些解释:
{% load algorithms_tags %}
“algorithms_tags”是的名称.py
中创建的文件templatetags
目录(不包括扩展名){% show_algorithms %}
“show_algorithms”是函数的装饰着名register.inclusion_tag
的inclusion_tag.py
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句