2

I have layout

    <block class="Magento\Framework\View\Element\Template" name="header" 
          template="Vendor_Module::header/notice.phtml" before="-"/>

In my template I do the following :

echo get_class($block); // Magento\Framework\View\Element\Template

echo get_class($this); // Magento\Framework\View\TemplateEngine\Php

$block - indicates my block defined in the layout

Why do I need $this ?

1
  • 1
    you do not need $this, And $block to access you block methods.
    – kunj
    Aug 21, 2018 at 11:40

3 Answers 3

2

Chances are, you don't.

Alan Storm covered this topic well in his article Magento 2: $block and $this are NOT Interchangeable. Now there are some methods in the Magento\Framework\View\TemplateEngine\Php class you might want, helper being an example.

Generally speaking you want to interact with your block class and $block is the correct variable to use for that.

As to why it exists, it's just because of how the templating system is built. Some insight about that exists in the Alan Storm article and also check out these questions - Difference Between $block and $this magento 2, Magento 2 Templates: Use `$block` or `$this`?.

0

You can create helpers in template using $this->helper("\Magento....")

0

You should not be using $this inside templates, use $block to access your block's methods.

Your Answer

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

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