Is there a way to filter a matrix by block type, or get a count of how many items there are of a certain type? Can't find a syntax example.

I created a matrix with two blocks. In pseudo code, basically what I want to do is this:

{% set typeOneBlocks = theMatrix blocks where type == "typeOne" %}

{% if typeOneBlocks != null %}
    <div class="divAWrapper">
        {% for block in typeOneBlocks %}
            <div class="divA">{# do stuff #}</div>
        {% endfor %}
{% endif %}

Same with typeTwo blocks. If there are no items of one type or the other, I don't want to create that container and have it sitting empty.

If there is not a way to filter or get a count, I'd have to use for loops to increment vars for how many of each block type there are and then act based on those counts. Seems there should be a simpler way.

2 Answers 2


You can grab a specific block type in Matrix by doing this:

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

If you wanted to know the number of blocks of a certain type, you can do:

{% set blocks = entry.myMatrixField.type('typeOne') %}
{{ blocks | length }}

If you want to search for multiple block types, you can do this:

{% set blocks = entry.myMatrixField.type('typeOne, typeTwo') %}

For your specific example, it would look like this:

{% set typeOneBlocks = entry.myMatrixField.type('typeOne') %}

{% if typeOneBlocks | length %}
    <div class="divAWrapper">
        {% for block in typeOneBlocks %}
            <div class="divA">{# do stuff #}</div>
        {% endfor %}
{% endif %}
  • 1
    6 minutes for a reply? Seriously, you guys are amazing. I'm not sure if I missed the documentation or if you just added it, but thanks for the quick help. buildwithcraft.com/docs/matrix-fields Jul 10, 2014 at 19:59
  • It's been in the docs for awhile. :)
    – Brad Bell
    Jul 10, 2014 at 20:21
  • @BradBell I 'd like to filter matrix block by category field. could you please guide for the same. Jan 8, 2015 at 14:02

In my Case i had to add .all() at the end then it worked with the Verison "Craft Solo"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.