سؤال

This is my first Template Tag where I'm interacting with a context variable. So I'm probably doing something wrong.

I want to pass in a PK for an object. So, something like this:

{% get_checkbox with object.id %}

That will use object.id to do a get for that object. If it exists render some HTML, if not render different HTML. I'm doing this as a template tag because I'll be doing more advance filtering once I have the record. But I need to get the context variable first.

Then in the template tag I want to do something like this:

from django import template
from project.app.models import Model


register = template.Library()


class ModelNode(template.Node):
    def __init__(self, object_id):
        self.object_id = template.Variable(object_id)

    def render(self, context):
        o_id = self.object_id.resolve(self.object_id)
        obj = Model.objects.get(id=o_id)
        if obj:
            return '<h3>Not yet</h3>'
        else:
            return '<h3>Go ahead</h3>'


@register.tag
def get_checkbox(parser, token):
    """
    Usage::
        {% get_checkbox with [object_id] %}

    """
    bits = token.contents.split()
    tag_name = bits[0]

    if len(bits) != 3:
        raise template.TemplateSyntaxError, "%s tag takes exactly two arguments" % (tag_name)
    if bits[1] != 'with':
        raise template.TemplateSyntaxError, "second argument to the %s tag must be 'with'" % (tag_name)

    object_id = bits[2]

    return ModelNode(object_id)

But I'm getting the following error:

VariableDoesNotExist at /app/
Failed lookup for key [object] in u'object.id'

It seems like the variable isn't getting resolved in the template tag?

I'd love suggestions and corrections. Thanks for your time.

هل كانت مفيدة؟

المحلول

The issue is the following line:

o_id = self.object_id.resolve(self.object_id)

It should be:

o_id = self.object_id.resolve(context)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top