【问题标题】:Django Template For Loop: How do you perform an action for the first record?Django 循环模板:如何为第一条记录执行操作?
【发布时间】:2023-03-06 06:39:01
【问题描述】:

我知道 django 故意不允许模板中包含大量逻辑。但是,有时您需要评估某些内容并基于此更改您的选择。

如何更改模板中的值或仅插入第一条记录?但是您仍然希望循环浏览其余部分。比如下面我的模板代码:

    {% for object in object_list %}
     <div id="t{{ object.id }}-header" class="content_headings title_highlight" >{{ object.title }}</div>
     <div id="t{{ object.id }}-content">
         ......

PHP 模板中的类似代码:

<div id="t<?php if ($i != 1) { echo $i-1; } ?>-header" class="content_headings<?php if ($i == 1) { ?> title_highlight<?php } ?>" ><?php the_title(); ?></div>  
<div id="t<?php if ($i != 1) { echo $i-1; } ?>-content">

【问题讨论】:

  • 在文档中找到这个: {% if forloop.first %} ,但代码似乎仍然不起作用。

标签: django django-templates


【解决方案1】:

forloop.first 是要走的路。我认为你需要做的就是稍微改变 Tiago 的答案,然后得到这样的结果:

{% for object in object_list %}
    <div id="t{% if not forloop.first %}{{ object.id }}{% endif %}-header" class="content_headings{% if forloop.first %} title_highlight{% endif %}">
        {{ object.title }}
    </div>
    <div id="t{% if not forloop.first %}{{ object.id }}{% endif %}-content">
{% endfor %}

我已经根据你的 PHP 代码检查了它,它似乎做的几乎完全相同(我没有从 {{ object.id }} 中取 1,因为只要 ID 是唯一的,它就不应该有所作为,对吧? )

【讨论】:

  • 感谢工作,虽然我认为 JS 可能存在问题,但它实际上不会突出显示。所以目前使用 firebug 来找出为什么 PHP 版本可以工作,但 django 版本不行
  • 通过文件比较程序(如果你在 OS X 上使用 FileMerge)运行 PHP 的 HTML 输出和 Django 的 HTML 输出,看看有什么不同。如果 JS 使用的是 PHP 生成的 HTML,那么它一定是 Django 模板中的 HTML 问题。不过,Firebug 最终可能会给你答案。
【解决方案2】:
{% for object in object_list %}
<div id="t{{ object.id }}-{%if forloop.first%}header{%else%}content{%endif%}" class="content_headings title_highlight" >{{ object.title }}</div>
...

【讨论】:

  • 感谢您的回复,您的 PHP 代码实际上并没有执行您上面的操作。 PHP 代码检查它是否是第一个值,然后添加一个新类。它为任何大于 1 的 != -1 位的值输出一个 ID...
  • 嗨 Issy,我很抱歉,但我不明白你想要做什么以及为什么 forloop.first 不起作用。你能澄清一下吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-10
  • 2017-01-11
  • 2017-07-27
  • 2018-09-08
  • 1970-01-01
  • 2021-07-30
  • 2012-01-20
相关资源
最近更新 更多