Matrix Block Generator
Design and generate Craft CMS Matrix field block type configurations.
// Add block types on the left to generate your Matrix template
Craft CMS Matrix Block Generator — How It Works
The Matrix field is Craft CMS's most powerful content modeling tool, enabling flexible "page builder" style layouts where editors can add, reorder, and configure different types of content blocks within a single field. Each block type has its own set of inner fields, and templates render each type differently using a switch statement.
This generator produces a complete Twig template with a {% for %} loop and {% switch %} block — the standard pattern for rendering Matrix fields in Craft CMS. Define your block type handles, optionally add a description, and the generator outputs a working template you can paste directly into your project.
Craft 5 Matrix Changes
Matrix was significantly redesigned in Craft 5. Block types are now nested entries — each block is a full Entry element with its own entry type. The iteration variable changes from block to entry, and the type check changes from block.type.handle to entry.type.handle. Inner field handles are now scoped to their entry type, so the pattern entry.myFieldHandle works as expected within a block's case body.
When upgrading a Craft 4 site to Craft 5, every Matrix template loop needs to be updated. The generator's Craft 4 mode uses the old block variable and block.type.handle syntax to make it easy to understand the diff when planning your upgrade.
The {% switch %} Tag
Craft CMS extends Twig with a custom {% switch %} / {% case %} / {% default %} tag that mirrors switch/case logic from PHP and JavaScript. It is cleaner and more readable than a chain of {% if %} / {% elseif %} checks, and it is the idiomatic way to handle Matrix block type routing in Craft templates. The {% default %} case acts as the fallback for any unrecognized block type handle.
Best Practices for Matrix Templates
- Always include a
{% default %}case to catch any block type handles you have not yet added to the template. - Wrap each case in a
<div>with a BEM-style class likeblock-richTextfor clean CSS targeting. - Use eager loading on the Matrix field and its inner relational fields together:
.with(['contentBuilder', 'contentBuilder.image']). - Keep block templates focused — extract complex block markup into partial templates using
{% include %}for better maintainability.