2016-05-23 115 views
1

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

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

设置文件如下,

enter image description here

+1

这里的东西没有意义;您的包含标签正在呈现使用标签本身的模板。 –

+0

另外'templates'目录应该位于你的app目录中,而不是项目的根目录,除非你已经明确地告诉Django去看那里。 – solarissmoke

+0

我认为你误解了包含标签的作用。包含标签呈现*另一个*模板。由于您在块外部有'{%results poll%}',因此标记的结果将永远不会显示。也许你想要一个[作业标签](https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#assignment-tags)代替(在Django 1.9中,你可以使用简单的标签而不是分配标签)。 – Alasdair

回答

2

如果您正在使用包含标记,则标记呈现另一个模板。您需要将使用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 %} 

如果你想将项目添加到模板的上下文,而不是渲染另一个模板,然后你想有一个simple tag来代替。

@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+简单的标记。在早期版本中,您需要assignment tag

+0

当你说一个'item'时,你的意思只是一个字符串,或者可能仍然是查询的结果,这是我希望以后的结果。但现在我只想简化它并在模板中加入“blah”。 –

+0

如果您正在使用简单标记,则结果可以是您喜欢的任何对象。你使用了一个字符串'blah',我把它改成了'['foo','blah']',因为它在循环模板列表中更有意义。如果你愿意,它可以是一个查询集。 – Alasdair

+0

模板应该在应用程序crudapp的模板目录中,即使我已经在settings.py中指定了模板是在问题中显示的文件中设置的位置吗? settings.py看起来像这样,TEMPLATES = [ {BACKEND':'django.template.backends.django.DjangoTemplates', 'DIRS':[os.path.join(BASE_DIR,“templates”)] ,. ........... –