In some cases, i hope not to0 many, you want to get content from a static block in Magento 2. You can use the following code snippet in your block to get the static block info by identifier name.
Create a block class
<?php
namespace Experius\CodeBlogStaticBlockContent\Block\Checkoutnotice;
class Index extends \Magento\Framework\View\Element\Template
{
protected $staticBlockRepository;
protected $filterProvider;
protected $storeManager;
protected $logger;
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);
}
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());
}
/* Optional ->setVariables(['number'=>213452345234] Usage in wysiwyfg
{{var number}} */
return __('Static block content not found');
}
public function getStaticBlockTitle(){
if($this->getStaticBlock()){
return $this->getStaticBlock()->getTitle();
};
return __('Whoops,');
}
}
Usage in your phtml
<?php
/**
*
* @var $block \Experius\CodeBlogStaticBlockContent\Block\StaticBlockContent\Index
*
*/
?>
<h1 class="page-title"><span class="base"><?php echo $block->getStaticBlockTitle(); ?></span></h1>
<div class="cms-content-important">
<?php echo $block->getStaticContent(); ?>
</div>
