[ACCEPTED]-Django templates and variable attributes-google-app-engine

Accepted answer
Score: 33

I found a "nicer"/"better" solution for 13 getting variables inside Its not the nicest 12 way, but it works.

You install a custom filter 11 into django which gets the key of your dict 10 as a parameter

To make it work in google 9 app-engine you need to add a file to your 8 main directory, I called mine django_hack.py which contains 7 this little piece of code

from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def hash(h,key):
    if key in h:
        return h[key]
    else:
        return None

register.filter(hash)

Now that we have 6 this file, all we need to do is tell the 5 app-engine to use it... we do that by adding 4 this little line to your main file

webapp.template.register_template_library('django_hack')

and in 3 your template view add this template instead 2 of the usual code

{{ user|hash:item }}

And its should work perfectly 1 =)

Score: 10

I'm assuming that the part the doesn't work 8 is {{ user.item }}.

Django will be trying a dictionary lookup, but 7 using the string "item" and not the value of the 6 item loop variable. Django did the same thing 5 when it resolved {{ user.name }} to the name attribute of the 4 user object, rather than looking for a variable 3 called name.

I think you will need to do some 2 preprocessing of the data in your view before 1 you render it in your template.

Score: 9

Or you can use the default django system 3 which is used to resolve attributes in tempaltes 2 like this :

from django.template import Variable, VariableDoesNotExist
@register.filter
def hash(object, attr):
    pseudo_context = { 'object' : object }
    try:
        value = Variable('object.%s' % attr).resolve(pseudo_context)
    except VariableDoesNotExist:
        value = None
return value

That just works

in your template 1 :

{{ user|hash:item }}
Score: 4

@Dave Webb (i haven't been rated high enough 6 to comment yet)

The dot lookups can be summarized 5 like this: when the template system encounters 4 a dot in a variable name, it tries the following 3 lookups, in this order:

* Dictionary lookup (e.e., foo["bar"])
* Attribute lookup (e.g., foo.bar)
* Method call (e.g., foo.bar())
* List-index lookup (e.g., foo[bar])

The system uses the 2 first lookup type that works. It’s short-circuit 1 logic.

Score: 3

As a replacement for k,v in user.items on 4 Google App Engine using django templates 3 where user = {'a':1, 'b', 2, 'c', 3}

{% for pair in user.items %}
   {% for keyval in pair %} {{ keyval }}{% endfor %}<br>
{% endfor %}

a 1
b 2 2
c 3

pair = (key, value) for each dictionary 1 item.

Score: 0

shouldn't this:

{{ user.item }}

be this?

{{ item }}

there is no user 1 object in the context within that loop....?

More Related questions