dongmian5325 2012-03-08 04:28
浏览 225
已采纳

Twig PHP:在Foreach中增加和减去一个值

I am working on a project that loops 100 times with repeating data. Every 8th post I am inserting an advertisement block, because I am using the index value to number each block output I need to subtract from a variable because the ad block isn't numbered. So the issue I have now is the following.

Block #1

Block #2

Block #3

Block #4

Block #5

Block #6

Block #7

Advertisement Block

Block #9

Because it is counting the advertisement block as one iteration of the index, the block that follows it which will have a number is now 9 when it should be 8. Is there a way to increment a variable and then subtract a value of 1 from it every time an advertisement block shows?

In standard PHP I could do this easy, but with Twig I've tried a few things and am at a loss as to what I can do.

  • 写回答

1条回答 默认 最新

  • douzhang1299 2012-03-08 05:42
    关注

    If i understandly correctly, you can do this:

    {% for foo in bar %}
      {% if (loop.index % 8 == 0 and loop.index > 0) %}
        {# You advertisement here #}
      {% endif %}
      {# Your standard block here #}
      <p>This is block #{{ loop.index + 1 + loop.index // 8 }}</p>
    {% endfor %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里