1

First sorry for my bad english.

What i want to do: display comments on a page, one at the right one at the left.

My code look like this:

{% for i in 0.. NbComment %}
   {% if  (i is divisibleby(2)) or (i == 0) %}

       <!--Right comment-->

   {% else %}

       <!--Left comment-->

   {% endif %}
{% endfor %}

It works perfectly except when I only have one comment: it display nothing. Thanks for your help.

1 Answer 1

2

Instead of divisableby I think using Twig's built-in odd/even test might be easier in this case:

{% for i in 0.. NbComment %}

   {% if i is odd %}

       <!--Right comment-->

   {% else %}

       <!--Left comment-->

   {% endif %}

{% endfor %}

And, just to suggest some minor improvements to your Twig, assuming the only difference between your comments is their alignment (left/right), you could do something like this, which would probably be a bit more DRY:

{% for i in 0.. NbComment %}

   <div class="comment is-{% i is odd ? 'odd' : 'even' %}">
      <!-- Comment content -->
   </div>

{% else %}

   <p class="error">No comments to display</p>

{% endfor %}

With the above code, your comments will have either the class .is-odd or the class .is-even – making it easy to e.g. float comments either left or right in your CSS. There's really no need to have a full if/else conditional.

Also, note the {% else %} statement in the above for loop. The contained markup will output if there are no comments – which is good practice, and will save you yet another conditional :)

3
  • Thanks it worked :) NbComment is a variable which count the number of comment i have . $nbComment = count($c) - 1;
    – Franck
    Commented Mar 22, 2015 at 12:09
  • Cool – I removed most of the answer to only contain the relevant part about using odd/even. Be advised that your loop will run (and print <!--Right comment--> even if NbComment is 0 :) Commented Mar 22, 2015 at 12:20
  • Hello @Franck, would you mind marking the above answer as accepted, if you're happy with it? Closing questions as "answered" helps keeping the site tidy and informative:) Commented Mar 23, 2015 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.