4

I am attempting to load a static block from my controller - but am having trouble locating the right syntax for doing this.

What is the proper syntax to load a CMS block by identifier or block id and what factory supports this type of loading?

asked Mar 1, 2016 at 19:21

1 Answer 1

9

On __construct function,you need inject

  • \Magento\Cms\Model\Template\FilterProvider
  • \Magento\Store\Model\StoreManagerInterface
  • \Magento\Cms\Model\BlockFactory

for getting data.

You can try below as example

.......
 public function __construct(
 \Magento\Framework\View\Element\Context $context,
 \Magento\Cms\Model\Template\FilterProvider $filterProvider,
 \Magento\Store\Model\StoreManagerInterface $storeManager,
 \Magento\Cms\Model\BlockFactory $blockFactory,
 array $data = []
 ) {
 parent::__construct($context, $data);
 $this->_filterProvider = $filterProvider;
 $this->_storeManager = $storeManager;
 $this->_blockFactory = $blockFactory;
 }
 protected function content()
 {
 $blockId = 'YOurBlock_Id';
 $html = '';
 if ($blockId) {
 $storeId = $this->_storeManager->getStore()->getId();
 /** @var \Magento\Cms\Model\Block $block */
 $block = $this->_blockFactory->create();
 $block->setStoreId($storeId)->load($blockId);
 $html = $this->_filterProvider->getBlockFilter()->setStoreId($storeId)->filter($block->getContent());
 }
 return $html;

}

answered Mar 1, 2016 at 19:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.