Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 786
nhuon Avatar asked Jan 12 '13 19:01

nhuon


People also ask

How do I register a tag library in Django?

Registering the tagThe tag() method takes two arguments: The name of the template tag – a string. If this is left out, the name of the compilation function will be used. The compilation function – a Python function (not the name of the function as a string).

What are template tags in Django?

The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. In the next chapters you will learn about the most common template tags.


1 Answers

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'
like image 199
Sergey Lyapustin Avatar answered Oct 15 '22 20:10

Sergey Lyapustin