Skip to main content

Display CMS Element in Frontend

Folder Structure

First, you should create block and element folders in your /Resources/views/storefront folder within your plugin:

  • Resources
    • config
    • views
      • storefront
        • block
        • element

In there, add the respective templates for your block/element. Name them like cms-block-my-block.html.twig or cms-element-my-element.html.twig respectively. my-block and my-element are the names you defined in the index classes of the Block/Element.

Block Template

In your Block, you'll need to load your respective content slots. Remember the slots: attribute in your Block main class? It'll look something like this:

slots: {
content: {
type: 'my-element'
}
}

This means we define that a component of the type my-element is going to be saved in the slot content.

To call this "content"-Slot, we use the getSlot() method of our block.slots property, and use it's .type name to build a sw_include name:

<div id="content">
{% set element = block.slot.getSlot('content') %}
{% sw_include "@Storefront/storefront/element/cms-element-" ~ element.type ~ ".html.twig" ignore missing %}
</div>

!> This is why naming the file the same as your component is so important, it makes this part a lot easier!

Element Template

From here, you probably know what you want to do. This is where you do all your html. Your Element config is accessed by {{ element.config }}. Try {{ dump(element.config) }} to show what's available.

If you use translated entities, you can get the translated value via the - you guessed it - translated property.