I'm using Google App Engine and Django templates.
I have a table that I want to display the objects look something like:
Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..]
The Django template is:
<table> <tr align="center"> <th>user</th> {% for item in result.items %} <th>{{item}}</th> {% endfor %} </tr> {% for user in result.users %} <tr align="center"> <td>{{user.name}}</td> {% for item in result.items %} <td>{{ user.item }}</td> {% endfor %} </tr> {% endfor %} </table>
Now the Django documention states that when it sees a . in variables
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...
If you need to make it available in some_other_template. html, all you need to do is to pass the RequestContext object as the third parameter to render_to_reponse().
A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.
Variable names consist of any combination of alphanumeric characters and the underscore ( "_" ) but may not start with an underscore, and may not be a number.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works.
You install a custom filter into django which gets the key of your dict as a parameter
To make it work in google app-engine you need to add a file to your main directory, I called mine django_hack.py which contains 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 this file, all we need to do is tell the app-engine to use it... we do that by adding this little line to your main file
webapp.template.register_template_library('django_hack')
and in your template view add this template instead of the usual code
{{ user|hash:item }}
And its should work perfectly =)
I'm assuming that the part the doesn't work is {{ user.item }}
.
Django will be trying a dictionary lookup, but using the string "item"
and not the value of the item
loop variable. Django did the same thing when it resolved {{ user.name }}
to the name
attribute of the user
object, rather than looking for a variable called name
.
I think you will need to do some preprocessing of the data in your view before you render it in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With