Django 模板和变量属性 [英] Django templates and variable attributes
问题描述
我正在使用 Google App Engine 和 Django 模板.
我有一个表,我想显示对象如下所示:
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},..]
Django 模板是:
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>
现在 Django 文档 指出,当它看到 .在变量
它尝试了多种方法来获取数据,其中之一是字典查找,这正是我想要的,但似乎没有发生...
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...
推荐答案
我找到了一个更好"/更好"的解决方案来获取内部变量这不是最好的方法,但它有效.
I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works.
您在 django 中安装了一个自定义过滤器,它以您的字典的键作为参数
You install a custom filter into django which gets the key of your dict as a parameter
要使其在 google app-engine 中工作,您需要将一个文件添加到您的主目录中,我调用了我的 django_hack.py,其中包含一小段代码
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 =)
这篇关于Django 模板和变量属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!