3

In magento2 I want to get the newsletter template or static block in my template.phtml.

I tried to use

<?php echo $this->getLayout()->createBlock("Magento\Newsletter\Block\Subscribe")->getTemplate('subscribe.phtml')->toHtml(); ?>

but without success. Can anyone help?

5
  • trying using setTemplate instead of getTemplate method May 30, 2016 at 9:48
  • i tried it, but not lucky.
    – xanka
    May 30, 2016 at 9:57
  • Where is the phtml file exactly located which you would like to set to the block ? May 30, 2016 at 10:01
  • i create custom file name is my-template.phtml in admin. so i want get newsletter template in my-template.phtml.
    – xanka
    May 30, 2016 at 10:11
  • Regarding the answers below, please use ->createBlock(Magento\Newsletter\Block\Subscribe::class) instead.
    – nevvermind
    May 31, 2016 at 10:27

2 Answers 2

5

The $this was right for Magento 1, however it is not for Magento 2.

Instead you should use $block.

On top of that you should set the template instead of getting it and then call the toHtml method that renders the block.

<?php echo $block->getLayout()->createBlock("Magento\Newsletter\Block\Subscribe")->setTemplate('Magento_Newsletter::subscribe.phtml')->toHtml(); ?>
6
  • it not show subscribe. i'm checked in system.log get [2016-05-30 09:52:32] main.CRITICAL: Invalid template file: 'Magento_Newsletter::subscribe.phtml' in module: 'Magento_Newsletter' block's name: 'subscribe_0' [] []
    – xanka
    May 30, 2016 at 9:54
  • @xanka flush the var/cache and var/generation folders May 30, 2016 at 9:55
  • my template in admin.
    – xanka
    May 30, 2016 at 10:13
  • @RaphaelatDigitalPianism : How can I call this in static block?? I've tried following {{block class="Magento\Newsletter\Block\Subscribe" template="Magento_Newsletter::subscribe.phtml"}} but not working Sep 26, 2016 at 12:13
  • 1
    @KaushalSuthar well that should work like that. Did you flush cache and compiled files ? Sep 26, 2016 at 12:16
1

Try this:

echo $this->getLayout()
          ->createBlock('Magento\Newsletter\Block\Subscribe')
          ->setTemplate('Magento_Newsletter::subscribe.phtml')
          ->toHtml(); 

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.