Working with blocks in Magento2 – Theme integration

Today we will dive into theming Magento2 by using blocks which are available on the client side (backoffice) and used within our templates and layout in our brand new Theme.

Let’s start by creating a block from the backend of our website.

Create a block on Magento2

Create a module to handle our block

$ mkdir -p app/code/YourCompany/YourModuleName/etc

Add a module.xml file and registration.php script relating to your module :


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd"&gt;
 <module name="Brand_module" setup_version="0.0.0"/>
</config>


<?php
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Brand_module', __DIR__);

You may use this command to issue a command from the Magento2 user :

sudo -u www-data php bin/magento module:enable Brand_module

sudo -u www-data php/bin/magento setup:upgrade

You may also add a tiny README.md file to document your module 🙂

Now add a Php class extending the Template framework as follow :


<?php
namespace Brand\Module\Block;

/**
* Brand block
*/
class MyClass extends \Magento\Framework\View\Element\Template
{
 public function getTitle()
 {
 return "Hello World !";
 }
}

Then create a template to reference our new block :


<?xml version="1.0"?&gt;
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd"&gt;
 <body>

 <referenceContainer name="header.container">
    <block class="Brand\Module\Block\HomePage" template="Brand_Module::default/home.phtml"/>
 </referenceContainer>
 </body>
</page>

You may refer to another container (check the default.xml file under Magento theme for instance…) to put your block inside (ex : main, header.container, footer …).

The cms_index_index.xml file is related to the home page exclusively, you can use different layouts depending on your needs, for instance :

  • catalog_product_view.xml for the default layout of a product detail page
  • catalog_category_view.xml for the layout of a category

You should already know that the default.xml file is used as the default layout for all kind of pages.

It only remains the template :


<?php
/**
* Brand Home view template
*
* @var $block BrandModuleBlockMyClass
*/
?>
<h1><?php echo $block->getTitle(); ?></h1>

 

From now on you can add a block to the right spot and carrying this along with css, you can do whatever you need to customize your theme.

Let’s go one step further by easing the modification of the text by the end user !

 

Load the content of a Bock updated on the administration interface of Magento2

We are talking about static content here and we will use the same type of code as above except the fact that we need to override the constructor in order to access context and static block repository.


<?php
namespace RHM\Custom\Block;

/**
* MCBL Home block
*/
class MyClass extends \Magento\Framework\View\Element\Template
{
protected $staticBlockRepository;
protected $filterProvider;
protected $storeManager;

protected $logger;

// constructor here
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Cms\Model\BlockRepository $staticBlockRepository,
\Magento\Cms\Model\Template\FilterProvider $filterProvider,
array $data = []
) {
$this->staticBlockRepository = $staticBlockRepository;
$this->filterProvider = $filterProvider;
$this->storeManager = $context->getStoreManager();
$this->logger = $context->getLogger();

parent::__construct($context, $data);
}

// Method to retrieve static filled from admin interface :
public function getStaticBlock(){
try {
return $this->staticBlockRepository->getById('static_block_identifier');
} catch(\Exception $e){
$this->logger->warning($e->getMessage());
}
return false;
}

public function getStaticContent(){

$staticBlock = $this->getStaticBlock();

if($staticBlock && $staticBlock->isActive()) {
    return $this->filterProvider
                ->getBlockFilter()
                ->setStoreId($this->storeManager->getStore()->getId())
                ->filter($staticBlock->getContent());
}

return __('We do not find this block, make sure it is available !');
}

public function getStaticBlockTitle(){
    if($this->getStaticBlock()){
      return $this->getStaticBlock()->getTitle();
    };
    return __('No title found here or no block defined with such id,');
}

}

Following is the way to retrieve the content of the static block :


<?php
/**
* View template for retrieving static content
*
* @var $block Brand\Module\Block\MyClass
*/
?>
<div class="content">
<?php echo $block->getStaticContent();?>
</div>

Check out the end result in black background :

Now test it out and change some text from the backoffice !

For further reading, you can browse the Magento2 documentation on file structure : Magento2 Module File Structure

Or stay here and check out our tutorials on Magento2.

If you have any comment, do not hesitate, I’ll be glad to answer and improve the content of this article.

Leave a Reply

Want more information?

Related links will be displayed here in this section for you to pick up another good spot to get more details about Web marketing and Search Engine Optimization. There will be some sites which we selected to ease the work of any webmaster or/and web marketer on the Internet.

%d bloggers like this: