2017-02-14 4 views
1

私はテンプレートの中でこのようなことをしたいと思います。djangoのテンプレートタグ内のテキスト内にコンテキスト変数を使用

{% include "blogs/blogXYZ.html" %} 

XYZ部分は可変である必要があります。つまり、どのようにコンテキスト変数をこの位置に渡すことができますか?たとえば、私が最初のブログを読んでいるなら、私はblog1.htmlを含めることができます。私が2番目のブログを読んでいるなら、blog2.htmlなどを含めることができます。それはdjangoで可能ですか?

+0

これはあなたを助けることができます。http://stackoverflow.com/questions/21483003/replacing- a-character-in-django-template – jape

答えて

1

次のアプローチは、動的テンプレート名を構築するためにstring.format機能を活用して、あなたが渡す必要があるとき、それはいくつかの問題が発生する可能性があり

...ランタイムにテンプレート名を構築するために、変数を受け入れるようにcustom tagを書くことができます2つ以上の変数を使用してテンプレート名を書式設定する必要があるため、要件を満たすために次のコードを修正してカスタマイズする必要があります。

your_app_dir/templatetags/custom_tags.py

from django import template 
from django.template.loader_tags import do_include 
from django.template.base import TemplateSyntaxError, Token 


register = template.Library() 


@register.tag('xinclude') 
def xinclude(parser, token): 
    ''' 
    {% xinclude "blogs/blog{}.html/" "123" %} 
    ''' 
    bits = token.split_contents() 
    if len(bits) < 3: 
     raise TemplateSyntaxError(
      "%r tag takes at least two argument: the name of the template to " 
      "be included, and the variable" % bits[0] 
     ) 
    template = bits[1].format(bits[2]) 
    # replace with new template 
    bits[1] = template 
    # remove variable 
    bits.pop(2) 
    # build a new content with the new template name 
    new_content = ' '.join(bits) 
    # build a new token, 
    new_token = Token(token.token_type, new_content) 
    # and pass it to the build-in include tag 
    return do_include(parser, new_token) # <- this is the origin `include` tag 

テンプレートでの使用:

<!-- load your custom tags --> 
{% load custom_tags %} 

<!-- Include blogs/blog123.html --> 
{% xinclude "blogs/blog{}.html" 123 %} 

<!-- Include blogs/blog456.html --> 
{% xinclude "blogs/blog{}.html" 456 %} 
+0

新しいテンプレート名が生成された後、 "return do_include(parser、template)"を使用しますか?なぜビットをさらに処理するのですか? –

+0

これは、テンプレート名のみを生成するために 'xinclude'パラメータが使用され、テンプレート名をビルドしたときにparamが不要になるためです。つまり、 'xinclude'は動的にタグを生成するために使われます:' {%include "blogs/blog123.html"%} ' – Enix

関連する問題