-
Notifications
You must be signed in to change notification settings - Fork 14
Creating Blocks
A block is an individual piece of content that can be reused throughout the whole site, you can create one from the page preview screen by clicking + Add block and giving it a name.
With our block created you can then define a schema for it which is just one or more fields that will be used to store the block's content. There are multiple field types available by default in Storyblok (text, textarea, wysiwyg, image, etc.) and you can know more about them in their Field Type Documentation.
After adding some custom field types and including the new block in our page we should see a debug message displayed where the block should be, this is a hint from the module to tell us that this is a new block and we have not yet created a template file in our theme to render it so let's go ahead and do that.
Out of the box our module doesn't include blocks, in fact we don't even add any extra CSS or JS to your Magento 2 store! We give you the freedom of customising your content any way you want using the technology stack of your choice.
The debug message above shows all the data that we have available as well as the path where it expects the PHTML template file to be in, so we just need to create a new file in MediaLounge_Storyblok/templates/story/block-name.phtml in our custom theme.
Inside this template we have access to the Storyblok fields as part of the block's data so you can access them by using the $block->getData()
method (or magic methods if you prefer).
MediaLounge_Storyblok/templates/story/block-name.phtml
<?php /** @var MediaLounge\Storyblok\Block\Container\Element $block */ ?>
<div>
<h1><?= $block->getTitle(); ?></h1>
<img src="<?= $block->getImage()['filename'] ?>" alt="<?= __('New Luma Collection') ?>">
</div>
Hint: You can see all the block's available data using
var_dump($block->getData())
Sometimes it is useful to nest blocks inside other blocks, eg: we could have a "Gallery" block with a "Title" and "Description" fields, as well as an "Media" field where we could nest "Image" or "Video" blocks.
Storyblok allows us to infinitely nest blocks and our integration module supports this functionality, all we need to do is use the $block->getChildHtml()
method in the location of our template where we want its child blocks to appear.
<?php /** @var MediaLounge\Storyblok\Block\Container\Element $block */ ?>
<div>
<h2><?= $block->getTitle(); ?></h2>
<p>
<?= $block->getDescription(); ?>
</p>
<?= $block->getChildHtml() ?>
</div>
There's nothing else to it, now any child component will be rendered inside this block using its own template.
Hint: Depending on the situation you might want to avoid nesting components and instead prefer to render them in the parent template. The child blocks are just an array of data still available in the parent template so it is a valid option to do so.