nhuon
nhuon

Reputation: 143

Django custom tags not rendered (GAE)

I'm trying to create Django custom tags with Google App Engine but for some reason it does not work all the time. I believe my tags are correctly registered as Django is parsing them but the render method is never called. The strangest thing is that my tags work when placed inside a for loop {% for ... %} but never outside.

Here's the code:

in django/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

in 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))

in main.html

{% foo %}

{% for item in items %}
    {% foo %}

and the result:

<django.mytags.FooNode object at 0x000000001794BAC8>

foo
foo
foo
...

This is driving me insane. I suspect putting my tag in a for loop forces the node to be rendered (where it should have been done already).

Upvotes: 9

Views: 471

Answers (2)

che
che

Reputation: 12263

Didn't you forget to add {% load mytags %}? (Should be used, per custom tag docs)

Upvotes: 0

Sergey Lyapustin
Sergey Lyapustin

Reputation: 1937

You need to add string representation for you class

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'

Upvotes: 1

Related Questions