2013-01-12 8 views
9

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' 
+0

ちょっと考えましたが、 '__unicode __()'関数を 'FooNode'クラスに追加するとどうなりますか? –

+0

@frb - この場合、__unicode __()を追加するだけで問題が隠されます。文字列を返すだけではなく、render()メソッドをパラメータとしてコンテキストで呼び出す必要があります。 – nhuon

+0

@nhuon:しかしrender()は常に文字列を返す必要があると思っています(空でも)。 P.S.なぜこれが起こっているのか分かりません。 __init __()が呼び出されていないようです。 – stellarchariot

答えて

1

あなたは{% load mytags %}を追加することを忘れないでいましたか? (custom tag docs

+0

文字列表現 – nhuon

+0

でうまく動作しました。実際には、私はまだ同じ問題があります。それはforループで動作し、外部では動作しません。 – nhuon

0

を文字列表現を追加する必要が

関連する問題