2016-05-23 20 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'ディレクトリは、Djangoに表示するよう明示的に指示していない限り、プロジェクトのルートではなく、あなたのappディレクトリの中にあるべきです。 – 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 

:ジャンゴ1.9+での簡単なタグの

{% fetch_result as result %} 

{% for item in result %} 
<p>This is {{ item }}</p> 
{% endfor %} 

{% fetch_result as result %}作品。以前のバージョンでは、assignment tagが必要です。

+0

あなたが 'item'と言うときは、ただ1つの文字列を意味するのでしょうか、それは依然としてクエリの結果かもしれません。しかし、今のところ私はそれを単純化し、テンプレートに「ああ」を得たいと思っていました。 –

+0

シンプルタグを使用している場合、結果は好きなオブジェクトになります。文字列 '' blah''を使用しましたが、テンプレートのリストをループするのが少し意味があるので、リスト['' foo '、' blah '] 'に変更しました。あなたが望むなら、それはクエリーセットになることができます。 – Alasdair

+0

ここでテンプレートは、apps.pyのテンプレートディレクトリにあるはずですが、settings.pyにはテンプレートが質問に表示されているファイルのどこにあるのかが特定されていますか? settings.pyは、TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates'、 'DIRS':[os.path.join(BASE_DIR、 "templates")]のようになります。 ... –

関連する問題