3

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.

Dwayne Charrington
  • 5,822
  • 7
  • 38
  • 62

1 Answers1

5

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 %}
Guillaume Poussel
  • 8,864
  • 1
  • 30
  • 39
  • Thank you, the logic inside of the printed out curly braces worked for me. I didn't know think of using arithmetic in the actual echo braces, I was too fixated on setting counters and variables to really try. – Dwayne Charrington Mar 08 '12 at 05:57