I have a Matrix block with a description field and a number field for hours. Let's say while creating an entry I add in 3 of these blocks with each having a different amount for the hours.

How can I add each of those 3 amounts and get a total amount?

I've spent quite a while researching and can't figure out what kind of syntax would make this work.

1 Answer 1


Twig allows you to add variables just as they were integers. You'll want to setup your totalHours variable before your loop begins so that the totalHours variable is available in the scope outside of the loop itself.

Something like this should work for you:

{# Create a variable to track your total hours #}
{% set totalHours = 0 %}

{% for block in entry.matrixFieldHandle %}

    {% if block.type == 'hoursBlock' %}
        {# Increment your total hours by adding the value
           of your hours block to the current totalHours #}
        {% set totalHours = totalHours + block.hoursFieldHandle %}
    {% endif %}

{% endfor %}

{# Output the result #}
Total Hours: {{ totalHours }}

While I can't test your specific code, here's a generic example that is doing the same thing that will work if you copy and paste it to your template:

{% set totalHours = 0 %}

{% for hours in 0..3 %}
    {% set totalHours = totalHours + hours %}
{% endfor %}

Total Hours: {{ totalHours }}
  • Perfect - It never occurred to me to set the variable initially blank and then iterate over it. Still new to this craft thing :) Thanks! Commented Aug 20, 2016 at 14:40

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.