Twig

The following is a basic example of how to render a Bloqs field with nested bloqs.

Note the include statements are passing an array of possible template names to include in the brackets. If the first template file is not found, it will skip it and attempt to render the next one. For example, if you have a bloq named "summary" and you want that bloq to render entirely different HTML, just create a template named _bloq_summary.html All other bloqs will render in the _bloq.html template. These template names are completely arbitrary and you can choose any names you want. In this example I have a coilpack.group folder with the _bloq.html.twig and _atom.html.twig templates inside.

entry.html.twig

{% for entry in exp.channel.entries.parameters(
    {'channel': 'pages', 'entry_id': '4'}
) %}
    <h1>{{ entry.title }}</h1>

    {% for bloq in entry.bloqs %}
        {% include [
            ('ee::coilpack._bloq_' ~ bloq.getDefinition().getShortName()),
            'ee::coilpack._bloq'
        ] with {
            'bloq': bloq
        } %}
    {% endfor %}

{% else %}
    <span>No blog entries</span>
{% endfor %}

_bloq.html.twig

{% set bloqName = bloq.getDefinition().getShortName() %}
{% set isComponent = bloq.getDefinition().isComponent() %}

<div class="{% if isComponent %}component{% else %}basic{% endif %}">
    {% for atom in bloq.getAtoms() %}
        {% include [
            ('ee::coilpack._atom_' ~ atom.getDefinition().getShortName()),
            'ee::coilpack._atom'
        ] with {
            'atom': atom
        } %}
    {% endfor %}

    {% for child in bloq.getChildren() %}
        {% include [
            ('ee::coilpack._bloq_' ~ child.getDefinition().getShortName()),
            'ee::coilpack._bloq'
        ] with {
            'bloq': child
        } %}
    {% endfor %}
</div>

_atom.html.twig

{# If your atom contains HTML, use the raw modifier, e.g. {{ atom | raw }} #}
{{ atom }}

If in this scenario there was an atom with the short name of "content_with_image", and a template file named _atom_content_with_image.html.twig existed, it would be loaded instead of the _atom.html.twig template.

Twig is extremly flexible and there are probably a number of ways to approach building out a Bloqs field. This is a basic example of how to use an include to render a deeply nested Bloqs field.

@todo Example of a Twig code to render a flat Bloqs field.

Other ways to access atom/field data.

Once you have a bloq variable you can access it's atoms and atom values directly via the dot notation:

{% for entry in exp.channel.entries.parameters(
    {'channel': 'pages', 'entry_id': '4'}
) %}
    <h1>{{ entry.title }}</h1>

    {% for bloq in entry.bloqs %}
        {{ bloq.heading }}
        {{ bloq.summary }}
    {% endfor %}
{% endfor %}

Last updated