【问题标题】:How to use variable in for loop using DJango如何使用 DJango 在 for 循环中使用变量
【发布时间】:2021-04-22 10:24:02
【问题描述】:

我可以在常规 python 中执行此操作,但在模板中似乎无法执行此操作。

所以这是我的变量:

PropertyID = ['A1','A2','A3']
filePaths = {A1:'['file1.jpg','file2.jpg','file3.jpg',]', A2:'['file1.jpg','file2.jpg','file3.jpg']'}

我的模板:

{% for properties in PropertyID %}
  {% for filePaths in imageFiles %}
    {% for singleFiles in filePaths %}

       

    {% endfor %}
  {% endfor %}
{% endfor %}

我希望能够动态地遍历文件路径,但是当我尝试时:

{% for singleFiles in filePaths.{{properties}} %}

我收到一个错误:

无法解析剩余部分:来自“filePaths.{{properties}}”的“{{properties}}”

我已经尝试过 filePaths['properties'] 和 filePaths[properties] 以及几乎所有的组合。我只是想不通为什么这不起作用。

如果我执行 filePaths.A1 它工作正常,但我不能以这种方式遍历其余路径。

任何帮助将不胜感激,可能我错过了一些非常愚蠢的事情。

【问题讨论】:

标签: python django for-loop django-templates


【解决方案1】:

您不能像那样访问字典键,而是可以在团队中使用 {% if %} 逻辑:

{% for properties in PropertyID %}
  {% for filePaths in imageFiles %}
    {% for propertyKey, singleFiles in filePaths.items %}
        {% if propertyKey == properties %}
           {% for singleFile in singleFiles %}
             // your code
           {% endfor %}
       {% endif %}
    {% endfor %}
  {% endfor %}
{% endfor %}

仅供参考,最好在视图而不是模板中执行这些操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2021-10-16
    相关资源
    最近更新 更多