【问题标题】:using variable inside of the template tags在模板标签内使用变量
【发布时间】:2013-06-05 12:50:54
【问题描述】:

我有以下示例结构

'_id': 1
'company': 'XXX'
'numberOfProducts': 2
'products': [
        {'sku': 'cnx1cs', 'name': 'canon', 'qty': 3},
        {'sku': 'nkx1cs', 'name': 'nikon', 'qty': 2}
         ]

当我在 html 文件(在 Django 中)中使用 {{list_of_assets.products.0.name}} 表示法时,它似乎比使用 dict.items()/dict.iteritems() 更舒服,尤其是当您考虑更多嵌套数组时。

但我不知道如何在 for 循环中控制数组项编号...

我的意思是,如果我们考虑上面的示例,我怎样才能通过在标签内以某种方式使用变量来迭代 for 循环两次并生成以下符号

    {{list_of_assets.products.0.name}}
    ....
    {{list_of_assets.products.1.name}}

问候

【问题讨论】:

    标签: arrays django pymongo


    【解决方案1】:

    你可以的

    {% for product in list_of_assets.products %}
      {{product.name}}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      Django 模板不允许复杂的循环结构或编程。 (有关模板 Philosophy 的完整详细信息,请阅读:http://www.djangobook.com/en/2.0/chapter04.html 部分:Philosophies and Limitations。

      也就是说,显示数组中所有项目的唯一方法是使用上面建议的解决方案 karthikr:

      {%for p in list_of_assets.products %}
          {{p.name}}
      {% empty %}
          Nothing in the list!
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2021-06-02
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        • 1970-01-01
        • 2014-06-12
        • 2014-08-09
        • 1970-01-01
        相关资源
        最近更新 更多