首页 > 解决方案 > 输出信息到模板(从下一个数组)

问题描述

停滞了,但我不明白如何显示下一个数组有这个:

return render(request, 'main.html', {'arrImages': arrImages,'title': arrTitle})

arrImages数组输出没有任何问题。但是如何获得title?我不明白我必须在哪里循环。

    <div class="container">
{% for images in arrImages %}
<hr>
    <p class="text-justify"> {{ /////????title }}</p>
    <img class = "col-12 ml-auto col-12 mr-auto" src={{ images }}>
{% endfor %}

我必须放在哪里{% for title in arrTitle %}{% endfor %},还是在一个循环中完成?抱歉有这样的问题,但在互联网上没有找到)

我通过 API 工作。没有数据库。如果有必要,我可以附上所有的代码views.py

标签: pythondjangodjango-templates

解决方案


简单字符串

如果title(顾名思义)只是一个简单的字符串,则不需要循环(因为遍历字符串意味着您遍历该字符串的字符)。因此,您可以在某处将其写为变量。例如:

<div class="container">
{% for images in arrImages %}
<hr>
    <p class="text-justify">{{ title }}</p>
    <img class = "col-12 ml-auto col-12 mr-auto" src={{ images }}>
{% endfor %}

字符串列表

如果它是一个字符串列表,并且每个字符串对应一个图像,那么您应该zip将这两个列表一起生成一个包含标题和图像源的元组的可迭代。尽管在模板中有扩展可以做到这一点,但在标准 Django 中,您通常zip(..)在视图中使用 a 来执行此操作:

return render(request, 'main.html', {'imageTitles': zip(arrImages, arrTitle)})

在模板中,我们需要解压这些 2-tuples:

<div class="container">
{% for image, title in imageTitles %}
<hr>
    <p class="text-justify">{{ title }}</p>
    <img class = "col-12 ml-auto col-12 mr-auto" src={{ image}}>
{% endfor %}

推荐阅读