Skip to content

Commit 4a1c8d2

Browse files
authored
Merge pull request #119 from diazwatson/108_EnhancementForThisInTemplateDoc
#108 Enhance doc for ThisInTemplate rule
2 parents 2a3889c + 65f6153 commit 4a1c8d2

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

Diff for: Magento2/Sniffs/Templates/ThisInTemplateSniff.md

+26-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,32 @@ In PHTML templates, the current block is available as `$this` and `$block`. The
66
`$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.
77

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

1111
## How to fix
1212

13-
Replace `$this` with `$block`. If you use private or protected methods, make them public.
13+
Replace `$this` with `$block`. If you use private or protected methods, make them public.
14+
15+
---
16+
17+
## Reasoning
18+
The use of helpers is in general discouraged therefore any `$this->helper(<helper_class>)` code used in PHTML templates should be refactored.
19+
20+
Consider using ViewModel instead.
21+
22+
## How to fix
23+
24+
Typical example of a helper being used in a PHTML:
25+
```html
26+
<?php $_incl = $block->helper(<helper_class>)->...; ?>
27+
```
28+
29+
Once the ViewModel is created, call it in the PHTML as follow:
30+
31+
```html
32+
<?php $viewModel = $block->getViewModel(); ?>
33+
```
34+
or
35+
```html
36+
<?php $viewModel = $block->getData('viewModel'); ?>
37+
```

0 commit comments

Comments
 (0)