Skip to content

#108 Enhance doc for ThisInTemplate rule #119

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions Magento2/Sniffs/Templates/ThisInTemplateSniff.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,32 @@ In PHTML templates, the current block is available as `$this` and `$block`. The
`$this` in templates is a legacy from Magento 1. It still works, however this can change any time, should templates and blocks be further decoupled. That's why for new code you should always use `$block` and restrict it to public methods.

## How it works
Any occurence of `$this` in PHTML files (via file pattern in ruleset.xml) raises a warning.
Any occurrence of `$this` in PHTML files (via file pattern in ruleset.xml) raises a warning.

## How to fix

Replace `$this` with `$block`. If you use private or protected methods, make them public.
Replace `$this` with `$block`. If you use private or protected methods, make them public.

---

## Reasoning
The use of helpers is in general discouraged therefore any `$this->helper(<helper_class>)` code used in PHTML templates should be refactored.

Consider using ViewModel instead.

## How to fix

Typical example of a helper being used in a PHTML:
```html
<?php $_incl = $block->helper(<helper_class>)->...; ?>
```

Once the ViewModel is created, call it in the PHTML as follow:

```html
<?php $viewModel = $block->getViewModel(); ?>
```
or
```html
<?php $viewModel = $block->getData('viewModel'); ?>
```