Django的include_tag内容不显示 [英] Django inclusion_tag contents not displaying

查看:561
本文介绍了Django的include_tag内容不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获取include_tag的内容显示。我没有得到错误,所以我知道标签正在注册,我几乎可以肯定它正确加载。该标记是在crudapp / templatetags / crudapp_tags.py中创建的。

I cannot get the contents of an inclusion_tag to display. I am not getting an errors so i know that the tag is registering and I am almost certain that it is loading correctly. The tag is created in crudapp/templatetags/crudapp_tags.py

from django import template
register = template.Library()

@register.inclusion_tag("forum.html")
def results(poll):
    form = 'blah'
    return {'form': form}

templates / forum.html

templates/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 %}

设置的文件如下,

推荐答案

如果你正在使用包含标签,然后该标签会渲染另一个模板。您需要将表单的代码从 forum.html 中移动到新模板中,例如 results.html

If you are using an inclusion tag, then the tag renders another template. You need to move the code that uses form out of forum.html and into a new template, e.g. results.html

results.html

results.html

{% if form %}
<p>Form exists</p>
{% endif %}
{% for item in form %}
<p>This is {{ item }}</p>
{% endfor %}

然后更改您的标签以使用此模板

Then change your tag to use this template

@register.inclusion_tag("results.html")
def results(poll):
    form = 'blah'
    return {'form': form}

最后,由于您正在扩展一个模板,您需要移动,然后将其标记为块,否则结果将不会被使用。

Finally, since you are extending a template, you need to move then tag into a block, otherwise the result won't be used.

{% block homepage %}
{% results poll %}
...
{% endblock %}

如果要将项目添加到模板上下文中,而不是渲染另一个模板,则需要一个简单标签

If you want to add an item to the template context instead of rendering another template, then you want a simple tag instead.

@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+中的简单标签。在早期版本中,您需要分配代码

The {% fetch_result as result %} works for simple tags in Django 1.9+. In earlier versions, you want an assignment tag.

这篇关于Django的include_tag内容不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆