Craft CMS : How to get matrix field value?

  • Post author:
  • Post category:Craft CMS

In Craft CMS, if you want to get the value of a Matrix field within a loop, you’ll need to access the specific block types and their fields. Assuming that the header field is a Matrix field with a block type named navLinks, and within the navLinks block type, you have a linkDestination field and a linkText field, you can modify your code as follows:

{% for block in header.navLinks.all() %}
    {# Accessing fields within the Matrix block #}
    {% set destination = %}
    {% set linkText = block.linkText %}

    {# Outputting HTML based on Matrix block fields #}
    <li><a href="{{ destination.url }}">{{ linkText }}</a></li>
{% endfor %}

This assumes that:

  • header is your Matrix field.
  • navLinks is a block type within the Matrix field.
  • linkDestination and linkText are fields within the navLinks block type.

Make sure to adjust the field names according to your Craft CMS setup. The one() method is used assuming that linkDestination is an Entries field or similar. If it’s a plain text field, you might not need the one() method.