如何基于查询结果数组,用Twig每4次迭代生成含嵌套区块的HTML区块?
Got it, let's work through how to build this Twig template for your 66-entry dataset. The goal is to group entries into chunks of 4, each wrapped in a parent HTML block with nested child blocks for individual entries—here's a straightforward implementation:
Step 1: Group Your Data with the batch Filter
Twig’s batch filter is made for this exact scenario: splitting an array into smaller chunks of a specified size. We’ll use it to turn your 66-item array into groups of 4.
{# Assume your query result is stored in the variable `danceEntries` #} {% set groupedEntries = danceEntries|batch(4) %}
This will create an array of arrays: 16 groups with 4 entries each, plus one final group with 2 entries (since 66 isn’t a perfect multiple of 4).
Step 2: Render Parent Blocks with Nested Child Entries
Now loop through each group to create a parent block, then nest loops for each entry in the group to build the child blocks. Here’s the full template code:
{# Group the entries into chunks of 4 #} {% set groupedEntries = danceEntries|batch(4) %} {# Loop through each parent block group #} {% for group in groupedEntries %} <div class="parent-block"> <h3>Dance Block {{ loop.index }}</h3> {# Optional: Number each parent block #} {# Loop through entries in the current group #} {% for entry in group %} {% if entry %} {# Safely handle the final partial group #} <div class="child-entry"> <div class="entry-header"> <span class="entry-number">#{{ entry.numero }}</span> <h4>{{ entry.coreo }}</h4> </div> <div class="entry-details"> <p><strong>Club:</strong> {{ entry.club }} ({{ entry.nazione }})</p> <p><strong>Number of Dancers:</strong> {{ entry.elementi }}</p> <p><strong>Dancers:</strong></p> <ul> {% for dancer in entry.ballerini %} <li>{{ dancer.nome }} ({{ dancer.sesso }})</li> {% endfor %} </ul> </div> </div> {% endif %} {% endfor %} </div> {% endfor %}
Key Details to Note:
- The
loop.indexvariable in the outer loop lets you number each parent block (e.g., "Dance Block 1", "Dance Block 2")—feel free to remove this if you don’t need it. - The
{% if entry %}check is optional but prevents rendering empty child blocks in the final group (sincebatchfills out partial groups withnullvalues by default). - All the CSS classes (
parent-block,child-entry, etc.) are placeholders—you can rename them to match your project’s styling system.
If you need to adjust the chunk size later (say, from 4 to 5), just change the number passed to batch()—it’s that flexible!
内容的提问来源于stack exchange,提问作者sihciv

