Google App EngineでDjangoカスタムタグを作成しようとしていますが、なんらかの理由でそれが常に機能しません。私はDjangoがそれらを解析しているのに、レンダリングメソッドが呼び出されないので、自分のタグが正しく登録されていると思います。私のタグは、forループ{%for ...%}の中に置かれたときには動作しますが、外側には置かれないというのが最も奇妙なことです。Djangoカスタムタグがレンダリングされない(GAE)
ここでは、コードです:main.htmlを
{% foo %}
{% for item in items %}
{% foo %}
結果で
ジャンゴで/mytags.py
from django import template
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
# This works all the time
@register.simple_tag
def hello_world():
return u'Hello world'
@register.tag('foo')
def foo(parser, token):
return FooNode()
class FooNode(template.Node):
def __init__(self):
self.foo = 'foo'
def render(self, context):
return self.foo
main.pyで
from google.appengine.ext.webapp import template
template.register_template_library('django.mytags')
...
self.response.out.write(template.render('main.html', template_values))
は、 :
<django.mytags.FooNode object at 0x000000001794BAC8>
foo
foo
foo
...
これは私を狂ってしまう。私はforループに自分のタグを置くことで、ノードがレンダリングされるようになっているのではないかと推測しています。あなたはクラスの
class FooNode(template.Node):
def __init__(self):
self.foo = 'foo'
def render(self, context):
return self.foo
def __unicode__(self):
return 'string to put in template'
ちょっと考えましたが、 '__unicode __()'関数を 'FooNode'クラスに追加するとどうなりますか? –
@frb - この場合、__unicode __()を追加するだけで問題が隠されます。文字列を返すだけではなく、render()メソッドをパラメータとしてコンテキストで呼び出す必要があります。 – nhuon
@nhuon:しかしrender()は常に文字列を返す必要があると思っています(空でも)。 P.S.なぜこれが起こっているのか分かりません。 __init __()が呼び出されていないようです。 – stellarchariot