在jinja循环中输出两个参数。

huangapple go评论207阅读模式
英文:

Output in jinja loop two parameters

问题

我正在使用Django进行开发。输出数据通过以下方式传递给HTML页面:

  1. def page(request):
  2. data = { 'name': [
  3. 'nameOne',
  4. 'nameTwo',
  5. 'nameThree'
  6. ],
  7. 'id': [
  8. '1',
  9. '2',
  10. '3'
  11. ]
  12. }
  13. return render(request, "mainpageapp/page.html", data)

我想要在链接中显示文本名称和值ID:

  1. <a href="/{{id}}">{{name}}</a>

目前,我只能在for循环中输出一个元素:

  1. {% for el in name %}
  2. <a href="/{{el}}">{{el}}</a><br>
  3. {% endfor %}

是否可以在一个for循环中显示两个字典元素?或者有其他实现方式吗?

英文:

I'm developing with Django. The output data is passed to the html page as follows:

  1. def page(request):
  2. data = { &#39;name&#39;:[
  3. &#39;nameOne&#39;,
  4. &#39;nameTwo&#39;,
  5. &#39;nameThree&#39;
  6. ],
  7. &#39;id&#39;:[
  8. &#39;1&#39;,
  9. &#39;2&#39;,
  10. &#39;3&#39;
  11. ]
  12. }
  13. return render( request, &quot;mainpageapp/page.html&quot;, data)

I would like to see a link with text name and value id

  1. &lt;a href=&quot;/{{id}}&quot;&gt;{{name}}&lt;/a&gt;

At the moment I can only output one element in the for loop

  1. {% for el in name %}
  2. &lt;a href=&quot;/{{el}}&quot;&gt;{{el}}&lt;/a&gt;&lt;br&gt;
  3. {% endfor %}

Is it possible to display two dictionary elements in one forloop? Or some other way to implement this?

答案1

得分: 2

将两个对象压缩成一个可迭代对象:

  1. def page(request):
  2. name = ['nameOne', 'nameTwo', 'nameThree']
  3. ids = ['1', '2', '3']
  4. data = zip(ids, name)
  5. context = {'data': data}
  6. return render(request, 'mainpageapp/page.html', context)

在模板中,我们可以使用以下方式进行枚举:

  1. {% for pk, name in data %}
  2. &lt;a href="/{{ pk }}">{{ name }}&lt;/a>&lt;br&gt;
  3. {% endfor %}

注意:请不要将变量命名为id,这会覆盖对内置函数id的引用。可以使用ids等其他名称。

英文:

Zip the two into a single iterable:

<pre><code>def page(request):
name = ['nameOne', 'nameTwo', 'nameThree']
ids = ['1', '2', '3']
data = <b>zip(ids, name)</b>
context = {'data': data}
return render(request, 'mainpageapp/page.html', context)</code></pre>

in the template, we then enumerate with:

<pre><code>{% for <b>pk, name in data</b> %}
&lt;a href=&quot;/{{ pk }}&quot;&gt;{{ name }}&lt;/a&gt;&lt;br&gt;
{% endfor %}</code></pre>


> Note: Please do not name a variable id, it overrides the reference to the id builtin function&nbsp;<sup>[Python-doc]</sup>. Use for example ids.

huangapple
  • 本文由 发表于 2023年7月27日 16:25:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定