My use is case is that I wish to show an advert every 3rd comment.
The forum module added the comment field to the forum content type. So the field name is comment_forum.
I have a block that contains the embed code for the ads. Using twig_tweak module to render that block in my template using {{ drupal_entity('block_content', '5') }}
I then created a template file called field--comment-forum.html.twig.
So far I have this:
{%
set classes = [
'field',
'field--name-' ~ field_name|clean_class,
'field--type-' ~ field_type|clean_class,
'field--label-' ~ label_display,
'comment-wrapper',
]
%}
{%
set title_classes = [
'title',
'comment-title-main',
label_display == 'visually_hidden' ? 'visually-hidden',
]
%}
{% if comments and not label_hidden %}
<div class="my-5 col-print-12" id="comment-container">
<section{{ attributes.addclass(classes) }}>
{{ title_prefix }}
<h2{{ title_attributes.addClass(title_classes) }} {{ attributes.setAttribute('id', 'comments') }}>{{ label }}</h2>
{{ title_suffix }}
{% 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 } %}
{% if loop.index0 is divisible by(3) %}
{{ item }}
<div class="ads">{{ drupal_entity('block_content', '5') }}</div>
{% else %}
{{ item }}
{% endif %}
{% else %}
<div class="comment-pager">{{ item }}</div>
{% endif %}
{% endfor %}
</section>
</div>
{% endif %}
{% if comment_form %}
<div class="container">
<div class="row justify-content-md-center">
<div class="col col-md-8 p-2 p-md-4 my-5 bg-light rounded comment-new-container d-print-none">
<h2 class="title comment-form__title comment-new-title">{{ 'Add new comment'|t }}</h2>
{{ comment_form }}
</div>
</div>
</div>
{% endif %}
This works, as in the block with the ads are shown every 3rd comment. However it messes up the markup.
Without the template the markup for a comment with replies is this:
This is the markup for the same comments with the above template:
I also notice the comments_ajax_pager_wrap
container div is also not included either. That's added by the comments_ajax_pager module.
This is my first Drupal 9 website. So I'm new to twig, any ideas? I feel like I may even be in the wrong template?
{% set item = { '#pre_render': pre_render, 0: item } %}
Why are you using that?