2

I am trying to get the content of a static block in a helper class. So far I had no luck. So, how can I get the content of a static block by block identifier in a helper class?

I tried:

$valueContent = $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('my_identifier')->toHtml();

Magento 2.2.2

| improve this question | | | | |
  • can you add any codes you tried – fmsthird May 10 '19 at 6:30
  • Sure, see my original post. – Arnie May 10 '19 at 6:32
0

Try something like below in your helper file.

<?php

namespace Custom\Module\Helper;

use Magento\Cms\Api\BlockRepositoryInterface;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    private $blockRepository;

    public function __construct(
        BlockRepositoryInterface $blockRepository
    ) {
        $this->blockRepository = $blockRepository;
    }

    public function getContent($identifier)
    {
        try {
            /** @var BlockInterface $block */
            $block = $this->blockRepository->getById($identifier);
            $content = $block->getContent();
        } catch (LocalizedException $e) {
            $content = false;
        }

        return $content;
    }
}

?>
| improve this answer | | | | |
0

You can try like this:

namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
     * @var \Magento\Framework\View\LayoutInterface 
     */
    protected $layout;


    /**
     * Data constructor.
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Framework\View\LayoutInterface $layout
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\View\LayoutInterface $layout
    ) {
        $this->layout = $layout;
        parent::__construct($context);
    }


    /**
     * @return block $valueContent
     */
    public function getBlock() {

        $valueContent = $this->getLayout()
            ->createBlock('Magento\Cms\Block\Block')
            ->setBlockId('my_identifier')
            ->toHtml();

        return $valueContent;

    }
}

Then you can use/call $helper->getBlock() to show it in a phtml template

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.