I am working on a site where site editors should be able to add, arrange, and remove matrix-style blocks that are a mixture of content created in Craft and data from an external source.

So for example:

Block 1: Heading
Block 2: Description
Block 3: External data
Block 4: Description

My preference would be to use module or a plugin to create fields, pull data, and define templates. I would prefer to NOT stuff all of this logic into Twig (though creating custom twig functions/filters wouldn't be terrible)

What is the best way to go about this?

1 Answer 1


Creating a complete custom field might be a bit overkill. In cases like these, I usually just create a matrix block that essentially acts as a placeholder for the external content. The matrix block may include some fields, like a headline to be displayed above the contents, or the background colour of the block. For example, I've recently built a matrix block that displays news items from an RSS feed. The matrix block included just a URL field to input the URL of the feed, and an integer field to specify the number of news items displayed.

You don't need to put all the logic into Twig. There are multiple ways to provide data or functions to Twig where the heavy lifting in terms of logic or data fetching is done in PHP - see Extending Twig for details.

In this case, I would probably create a Twig function, something like fetchExternalData() - use a more appropriate name that describes your particular use-case. You can create a simple Twig extension to make this function available to Twig. Then you can simply call this function from Twig:

{% set externalData = fetchExternalData() %}
{% for item in externalData %}
    {# … #}
{% endfor %}

The function should include caching, so that the external API request doesn't need to happen for every request.

The only reason to create a custom field would be if the editors need to see the external content in the control panel, and potentially edit or select from it. Or if the external content needs to be fetched once when the field / matrix block is created, and then stored to the database, so it can live there forever. In this case, see the documentation on creating a custom field type. I would probably start by extending one of the built-in fields, or see if there's a plugin that provides a field type that can serve as a starting point.

  • 2
    I agree with this, and would also add that the FeedMe plugin might potentially satisfy your needs: you can set up a cron job that automatically triggers, say, a nightly import of the external data, storing it in Craft where it can be accessed normally. Mar 20, 2023 at 9:05

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.