无法显示inclusion_tag的内容。我没有收到错误,所以我知道标签正在注册,而且我几乎可以肯定它是正确加载的。标记是在crudapp/templatetag/crudapp_tags.py中创建的。
from django import template
register = template.Library()
@register.inclusion_tag("forum.html")
def results(poll):
form = 'blah'
return {'form': form}模板/forum.html
{% extends 'index.html' %}
{% load crudapp_tags %}
{% results poll %}
<p>aaa</p>
{% block homepage %}
<p>bbb</p> <!-- Only this displays -->
{% if form %}
<p>Form exists</p>
{% endif %}
{% for item in form %}
<p>This is {{ item }}</p>
{% endfor %}
<div>
<p>{% if user.is_authenticated %}Add a New Topic: <a href="{% url 'topic_form' %}"><span class="glyphicon glyphicon-plus"></span></a>{% endif %}</p>
</div>
<div>
<p>{{ totalposts.count }} posts, {{ totaltopics.count }} topics, {{ totalusers.count }} users, {{ totalviews.numviews}} views</p>
</div>
{% endblock %}文件设置如下,

发布于 2016-05-23 13:01:16
如果使用包含标记,则标记将呈现另一个模板。您需要将使用form的代码移出forum.html并进入新模板,例如results.html
results.html
{% if form %}
<p>Form exists</p>
{% endif %}
{% for item in form %}
<p>This is {{ item }}</p>
{% endfor %}然后更改标记以使用此模板。
@register.inclusion_tag("results.html")
def results(poll):
form = 'blah'
return {'form': form}最后,由于要扩展模板,需要将标记移动到块中,否则将不会使用结果。
{% block homepage %}
{% results poll %}
...
{% endblock %}如果您想要向模板上下文添加一个项而不是呈现另一个模板,那么您需要一个简单标签。
@register.simple_tag
def fetch_result():
result = ['foo', 'bar']
return result然后在模板中:
{% fetch_result as result %}
{% for item in result %}
<p>This is {{ item }}</p>
{% endfor %}{% fetch_result as result %}适用于Django 1.9+中的简单标记。在早期版本中,您需要一个赋值标签。
https://stackoverflow.com/questions/37390990
复制相似问题