cliveportman/code

Calculate average of numbers in Craft CMS using Twig

Rebuilding Shopify's rating and review functionality in Craft, I wanted to get the average of a products ratings using Twig:

{% set reviews = craft.entries.section('reviews').relatedTo(entry).find() %}
{% set ratingsSum = 0 %}
{% if reviews | length %}
    {% for review in reviews %}
        {% set ratingsSum = ratingsSum + review.rating %}
    {% endfor %}
{% set ratingAverage = ratingsSum / reviews | length %}

On the front-end, I'm displaying the ratings using the amazing Raty plugin.