0

I would like to add a div for every comment on my field--comment.html.twig

On the template I've a "comments" variable, but if I cycle in this way, I obtain error (Fatal error: "0" is an invalid render array key in /var/www/html/core/lib/Drupal/Core/Render/Element.php on line 97):

{% for comment in comments %}
      {{ comment }}
  {% endfor %}

I would like to add "odd/even" class to comments.

[EDIT] If I use a cycle like this:

{% for key,value in comments %}
  {{ dump(key) }}
{% endfor %}

keys are: #sorted, #pre_render, 'pager', '106', '107' (where 106 and 107 are comment ids)

  • #pre_render is for cache performance, 106, 107, ...contain a minimal build of the comment and they are fully prepared for rendering only in case of a cache miss. If you don't care so much for performance you can try to render the single comments, see my answer. – 4k4 Jun 13 '18 at 16:43
4

You can try something like this:

   {% set pre_render = comments['#pre_render'] %}

   {% for key, item in comments if key|first != '#' %}
     {% if key != 'pager' %}
       {% set item = { '#pre_render': pre_render, 0: item } %}
       <div class="comment-{{ cycle(['odd', 'even'], loop.index0) }}">{{ item }}</div>
     {% else %}
       <div class="comment-pager">{{ item }}</div>
     {% endif %}
   {% endfor %}
  • This work for the cycle, but when it prints "item", it loose all "content" values (author, fields, etc). This "content" variable is in the comment.html.twig template – arrubiu Jun 14 '18 at 6:06
  • I think that the #pre_render value is mandatory to render the comment. Should I work on a preprocess function? – arrubiu Jun 14 '18 at 6:24
  • Yes, it seems like you need #pre_render. I think it should be possible in twig, see the edit. – 4k4 Jun 14 '18 at 6:56
  • yesss, it works, thanks a lot! The alternative could be to insert a views, but it's better in this way :) – arrubiu Jun 14 '18 at 7:09
1

Loop and set the odd-even classes by using following code:

  {% for comment in comments %}
            {% set classes = cycle(['odd', 'even'], loop.index0) %}
            <div{{ comment.attributes.addClass('comment-', classes ) }} >{{ comment}}</div>
    {% endfor %}
  • It doesn't work: Fatal error: "0" is an invalid render array key in /var/www/html/core/lib/Drupal/Core/Render/Element.php on line 97 I think that "comment", in the for cycle, is not a render array.. – arrubiu Jun 13 '18 at 9:07
  • Did u clear the cache ?? have a look at this link gist.github.com/NikLP/cb9adc963036d1ffd8896928de2b9b7a – Shreya Shetty Jun 13 '18 at 9:11
  • Of course :) your code is not different than mine, the problem is that "comment" is not a render array – arrubiu Jun 13 '18 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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