【问题标题】:How to get object attribute in django template for loop如何在 django 模板中获取对象属性以进行循环
【发布时间】:2015-01-02 07:54:22
【问题描述】:

你如何做相当于这个python for循环的Django模板?

    extra_context = [o.extra_context for o in activities] 

或者我需要注册一个新的模板标签吗?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    如果你想创建一个新的列表变量来迭代,你需要访问模板的上下文——我认为你不能从模板本身做到这一点。据我所知,必须从视图中完成。 This question may provide more insight. The discussion of template tags found in the same thread is also relevant.

    如果activities 是唯一通过请求上下文传递的东西,那么我相信您可以在模板中做的最接近的事情是:

    {% for o in activities %}
        {{ o.extra_context }}
        <!-- do stuff -- >
    {% endfor %}
    

    我会参考上面链接的线程来讨论制作可以与新列表一起使用的标签等。

    【讨论】:

      【解决方案2】:

      环顾四周并阅读一些文档后,这是我的方法

      {% for a in activities %}
          {% with a.extra_context as o %}
          {% endwith %}
      {% endfor %} 
      

      【讨论】:

        猜你喜欢
        • 2011-08-30
        • 2021-04-17
        • 1970-01-01
        • 2015-11-08
        • 1970-01-01
        • 2011-01-14
        • 2018-04-10
        • 1970-01-01
        • 2010-10-20
        相关资源
        最近更新 更多