How-to library · Developer docs

How-to library

Task-shaped pages: a title that starts with a verb, the situation in a few lines, the steps, the working code in both engines, and why this way rather than another. Found from a search, done, and left.

Add a component collection an author can fill

A collection is a layout area whose input type has the collection category. Add it to the layout, name the component layouts it accepts, and loop its elements in the template, rendering each element's component.

Context

Context. A "sections" area that an author fills with any number of blocks, in any order, is a component collection: a layout area whose input type has the collection category. Each entry is a collection element holding one component. The template loops the elements and renders each component through its own layout's template, so the page template never knows which blocks exist.

Steps

  1. On the page layout, add a layout area sections with the site's component-collection input type (category collection).
  2. Fill in its supported layouts: only the blocks that make sense in the page body. An empty list offers every component layout on the site.
  3. Set min and max if the design needs them (a hero row that takes exactly one, a gallery of at most twelve).
  4. Loop the elements in the template and render each component.

Template code

Template code
{$elements = $page->getAreaCollectionElements('sections')}
{if $elements->count() > 0}
<div class="sections">
{foreach $elements as $element}
  {$block = $element->getComponent()}
  {if !$block->isBlank()}{$block->getHtml(['index' => $element@iteration])}{/if}
{/foreach}
</div>
{/if}
{% set elements = page.getAreaCollectionElements('sections') %}
{% if elements|length > 0 %}
<div class="sections">
{% for element in elements %}
  {% set block = element.getComponent() %}
  {% if not block.isBlank() %}{{ block.getHtml({'index': loop.index}) }}{% endif %}
{% endfor %}
</div>
{% endif %}

Why this and not that

Not one component area per block ("section1", "section2"): the author cannot add a fifth or reorder, and the template hardcodes the count. Not getAreaHtml('sections') alone: it renders every element for you and is fine for a plain stack, but the loop is where you pass the index, the load priority and the heading level down. The variables you pass must be new names; a passed variable never overrides one the page already has.

Go deeper

Was this page helpful?

Your answer goes to the docs team.