English 中文(简体)
Django模板和变量属性
原标题:
  • 时间:2008-08-30 13:20:02
  •  标签:

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模板是:

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

最佳回答

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

您在django中安装了一个自定义过滤器,该过滤器将dict的密钥作为参数

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 )

并在您的模板视图中添加此模板,而不是通常的代码

{{ user|hash:item }}

它应该能完美工作=)

问题回答

我假设不起作用的部分是{{user.item}}

Django将尝试查找字典,但使用字符串“item”,而不是item循环变量的值。Django在将{{user.name}}解析为user对象的name属性时也做了同样的事情,而不是寻找一个名为name

我认为在将视图中的数据渲染到模板中之前,您需要对其进行一些预处理。

或者,您可以使用默认的django系统,该系统用于解析tempaltes中的属性,如下所示:

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

这很管用

在您的模板中:

{{ user|hash:item }}

@Dave Webb(我的评价还不够高,无法发表评论)

点查找可以这样总结:当模板系统在变量名中遇到点时,它会按以下顺序尝试查找:

* 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])

系统使用第一种有效的查找类型。这是短路逻辑。

作为谷歌应用引擎上user.items中k,v的替换,使用django模板,其中user={a:1,b,2,c,3}

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

a 1
b 2
c 3

pair=每个字典项的(键,值)。

不应该这样:

{{ user.item }}

是这样吗?

{{ item }}

在该循环的上下文中没有用户对象。。。。?





相关问题