Is this the most efficient way to use matrix in a template where different block types need outputting in various area of the HTML markup? I have 9 block types that need to be placed in various areas of the HTML markup.

{# Create a variable with the matrix fields in #}
{% set var = entry.sofa %}

{# Is the block in the variable #}
{% if var.block.type('twoSeaterSofa') %}

    {# block is in variable #}
    {% for block in var.block.type('twoSeaterSofa') %}      
        {# output block #}
        {{ block.price }}
    {% endfor %}

{% endif %}

Grateful for any advice or code.


The right syntax to filter matrix blocks by block type is this (see Craft docs here):

{% for block in entry.myMatrixField.type('text') %}{% endfor %}

So you only have to remove the extra .block you have in your example code. I'd save the returned array of MatrixBlockModels to a variable and use the length filter to see if there are any blocks of this type.

{% set twoSeaterSofas = entry.sofa.type('twoSeaterSofa') %}
{% set threeSeaterSofas = entry.sofa.type('threeSeaterSofas') %}

<!-- some HTML -->

{% if twoSeaterSofas|length %}
    {% for block in twoSeaterSofas %}    
    {% endfor %}
{% endif %}

<!-- more HTML -->

{% if threeSeaterSofas|length %}
    {% for block in threeSeaterSofas %}    
    {% endfor %}
{% endif %}

There are multiple ways of doing this, this is mine:

{# Loop through all blocks and include a file with the block's type(slug) #}
{% for block in entry.matrixFieldHandle %}
    {% include "includes/blockTypes/_" ~ block.type ignore missing %}
{% endfor %}

So, you need a folder, for instance blockTypes, within a folder includes (or whatever path you'd want to give those), with a file for every Matrix block type, prepended with '_'. I find this easy to work with, especially when dealing with large numbers of types.

The ignore missing part of the include makes sure that you don't get errors if a file is not found. So, if nothing gets displayed, chances are one or more files don't exist.

Within your include, you only use the code needed to show that type's fields:

{{ block.price }}
  • Did I get the question wrong or isn't he trying to group the matrix blocks by block type?
    – carlcs
    Jan 26 '15 at 15:20
  • carlcs, I think you're right! Ignore my answer, then ;)
    – Paul
    Jan 26 '15 at 15:21

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.