How do I out­put an Assets Field inside a Matrix Field inside an Entry Type?

The following is an outline for looping through a Single, Channel, or Structure entry with multiple Entry Types in which some of your Entry Types may include a Matrix Field and which some of your Matrix Field's blocks may include an Assets field.

Let's build our output step by step. First, let's build a template to check for each of our Entry Types. We want to make sure we are only trying to output the fields within each Entry Type, if that Entry Type exists.

{% if entry.type == 'post' %}
	
	{# Post Entry Type fields go here #}

{% elseif entry.type == 'link' %}

	{# Link Entry Type fields go here #}

{% elseif entry.type == 'video' %}

	{# Video Entry Type fields go here #}

{% endif %}

Our Post has a Matrix field with an Assets field within one of our Matrix blocks. We'll start by testing for each of our Matrix Blocks in a similar way to how we tested for our Entry Types. This time we'll use the switch statement, but a simple if statement would work as well.

{% for block in entry.matrixFieldHandle %}
	
	{% switch block.type %}

		{% case 'textBlock' %}

			{# Our Text Block fields go here #}

		{% case 'quoteBlock' %}

			{# Our Quote Block fields go here #}

		{% case 'imageBlock' %}

			{# Our Image Block fields go here #}

	{% endswitch %}	

{% endfor %}

Now that we have our framework, we can start outputting our individual fields within each block. In this article, we'll just focus on the Asset field in our image block. Our image block contains a gallery of images, so we will loop through our assets field to output all the images that it has.

{% for image in block.assetFieldHandle %}
    
	<img src="{{ image.getUrl() }}" width="{{ image.getWidth() }}" height="{{ image.getHeight() }}" alt="{{ image.title }}">
		
{% endfor %}

Now let's bring this all together. First we check for which Entry Type we have, then we check for which Matrix Block we have, and then we loop through all the images that we find.

{% if entry.type == 'post' %}
	
	{# Post Entry Type fields go here #}
	{% for block in entry.matrixFieldHandle %}
		
		{% switch block.type %}

			{% case 'textBlock' %}

				{# Our Text Block fields go here #}

			{% case 'quoteBlock' %}

				{# Our Quote Block fields go here #}

			{% case 'imageBlock' %}

				{# Our Image Block fields go here #}
				{% for image in block.assetFieldHandle %}
				    
					<img src="{{ image.getUrl() }}" width="{{ image.getWidth() }}" height="{{ image.getHeight() }}" alt="{{ image.title }}">
						
				{% endfor %}

		{% endswitch %}	

	{% endfor %}

{% elseif entry.type == 'link' %}

	{# Link Entry Type fields go here #}

{% elseif entry.type == 'video' %}

	{# Video Entry Type fields go here #}

{% endif %}

Level up in Craft CMS with practical examples, snippets, and patterns.
Craft The Planet emails are sent out several times a week.