【问题标题】:How to access dictionary value in jinja? Is it possible or not? If possible then how?如何在 jinja 中访问字典值?有没有可能?如果可能,那怎么办?
【发布时间】:2022-01-31 20:58:58
【问题描述】:

我正在尝试在 Django 项目中使用此代码 sn-p。
如何访问每个键的值(列表)?
并显示列表项?

我想使用 Jinja 显示这样的表格。 有可能吗?

key values
100 1,2
200 3,4
300 5,6
400 7,8

表中可能有数千行。

def index(request):

    data = {
        100: [{'childId': 1, 'childStructure': 'Leaf'}, {'childId': 2, 'childStructure': 'Intermediate'}],
        200: [{'childId': 3, 'childStructure': 'Intermediate'}, {'childId': 4, 'childStructure': 'Leaf'}],
        300: [{'childId': 5, 'childStructure': 'Leaf'}, {'childId': 6, 'childStructure': 'Intermediate'}],
        400: [{'childId': 7, 'childStructure': 'Intermediate'}, {'childId': 8, 'childStructure': 'Leaf'}],
    }

    return render(request,'index.html', {'data': data})

【问题讨论】:

    标签: dictionary jinja2 show


    【解决方案1】:

    您可以在字典上使用 for 循环。您只需使用dict.items() 即可,as pointed in the documentation

    给定模板:

    <table style="border: 1px solid">
      <tr>
        <th>key</th>
        <th>value</th>
      </tr>
    {% for key, value in data.items %}
      <tr>
        <td>{{ key }}</td>
        <td>{{ value | map(attribute='childId') | join(',') }}</td>
      </tr>
    {% endfor %}
    </table>
    

    这会给你:

    <table>
      <tr>
        <th>key</th>
        <th>value</th>
      </tr>
      <tr>
        <td>100</td>
        <td>1,2</td>
      </tr>
      <tr>
        <td>200</td>
        <td>3,4</td>
      </tr>
      <tr>
        <td>300</td>
        <td>5,6</td>
      </tr>
      <tr>
        <td>400</td>
        <td>7,8</td>
      </tr>
    </table>

    【讨论】:

    • 不幸的是它显示:Could not parse the remainder: '()' from 'data.items()'
    • 是的,没有 Django 中的 (),确实:{% for key, value in data.items %}
    猜你喜欢
    • 2021-07-29
    • 2019-11-03
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2018-10-31
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多