Skip to content

Commit ec30652

Browse files
committed
application: improved info about template variables and extensions
1 parent b456906 commit ec30652

2 files changed

Lines changed: 116 additions & 48 deletions

File tree

application/cs/templates.texy

Lines changed: 57 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,32 @@ Soubory, kde se dohledávají šablony layoutu, lze změnit překrytím metody [
114114
Proměnné v šabloně
115115
------------------
116116

117-
Proměnné do šablony předáváme tak, že je zapíšeme do `$this->template` a potom je máme k dispozici v šabloně jako lokální proměnné:
117+
Proměnné do šablony předáváme zápisem do `$this->template`. V šabloně jsou pak dostupné jako lokální proměnné:
118118

119119
```php
120120
$this->template->article = $this->articles->getById($id);
121121
```
122122

123-
Takto jednoduše můžeme do šablon předat jakékoliv proměnné. Při vývoji robustních aplikací ale bývá užitečnější se omezit. Například tak, že explicitně nadefinujeme výčet proměnných, které šablona očekává, a jejich typů. Díky tomu nám bude moci PHP kontrolovat typy, IDE správně našeptávat a statická analýza odhalovat chyby.
123+
124+
Výchozí proměnné
125+
----------------
126+
127+
Presentery a komponenty předávají do šablon několik užitečných proměnných automaticky:
128+
129+
- `$basePath` je absolutní URL cesta ke kořenovému adresáři (např. `/eshop`)
130+
- `$baseUrl` je absolutní URL ke kořenovému adresáři (např. `http://localhost/eshop`)
131+
- `$user` je objekt [reprezentující uživatele |security:authentication]
132+
- `$presenter` je aktuální presenter
133+
- `$control` je aktuální komponenta nebo presenter
134+
- `$flashes` pole [zpráv |presenters#Flash zprávy] zaslaných funkcí `flashMessage()`
135+
136+
Pokud používáte vlastní třídu šablony, tyto proměnné se předají, pokud pro ně vytvoříte property.
137+
138+
139+
Typově bezpečné proměnné
140+
------------------------
141+
142+
Při vývoji robustních aplikací je užitečné explicitně nadefinovat, jaké proměnné šablona očekává a jakého jsou typu. Získáte tak typovou kontrolu v PHP, chytré našeptávání v IDE a schopnost statické analýzy odhalovat chyby.
124143

125144
A jak takový výčet nadefinujeme? Jednoduše v podobě třídy a její properties. Pojmenujeme ji podobně jako presenter, jen s `Template` na konci:
126145

@@ -169,21 +188,6 @@ public function renderDefault(): void
169188
```
170189

171190

172-
Výchozí proměnné
173-
----------------
174-
175-
Presentery a komponenty předávají do šablon několik užitečných proměnných automaticky:
176-
177-
- `$basePath` je absolutní URL cesta ke kořenovému adresáři (např. `/eshop`)
178-
- `$baseUrl` je absolutní URL ke kořenovému adresáři (např. `http://localhost/eshop`)
179-
- `$user` je objekt [reprezentující uživatele |security:authentication]
180-
- `$presenter` je aktuální presenter
181-
- `$control` je aktuální komponenta nebo presenter
182-
- `$flashes` pole [zpráv |presenters#Flash zprávy] zaslaných funkcí `flashMessage()`
183-
184-
Pokud používáte vlastní třídu šablony, tyto proměnné se předají, pokud pro ně vytvoříte property.
185-
186-
187191
Vytváření odkazů
188192
----------------
189193

@@ -205,21 +209,44 @@ Více informací najdete v kapitole [Vytváření odkazů URL|creating-links].
205209
Vlastní filtry, značky apod.
206210
----------------------------
207211

208-
Šablonovací systém Latte lze rozšířit o vlastní filtry, funkce, značky apod. Lze tak učinit přímo v metodě `render<View>` nebo `beforeRender()`:
212+
Šablonovací systém Latte lze rozšířit o vlastní filtry, funkce, značky a další prvky. K dispozici jsou tři způsoby, jak to udělat, od nejrychlejších ad-hoc řešení až po architektonický přístup pro celou aplikaci.
213+
214+
**Ad-hoc v metodách presenteru**
215+
216+
Nejrychlejší způsob je přidat filtr nebo funkci přímo v kódu presenteru či komponenty. V presenteru je k tomu vhodná metoda `beforeRender()` nebo `render<View>()`:
209217

210218
```php
211-
public function beforeRender(): void
219+
protected function beforeRender(): void
212220
{
213221
// přidání filtru
214-
$this->template->addFilter('foo', /* ... */);
222+
$this->template->addFilter('money', fn($val) => round($val) . ' Kč');
223+
224+
// přidání funkce
225+
$this->template->addFunction('isWeekend', fn($date) => $date->format('N') >= 6);
226+
}
227+
```
228+
229+
V šabloně pak:
230+
231+
```latte
232+
<p>Cena: {$price|money}</p>
233+
234+
{if isWeekend($now)} ... {/if}
235+
```
236+
237+
Pro složitější logiku můžete konfigurovat přímo objekt `Latte\Engine`:
215238

216-
// nebo konfigurujeme přímo objekt Latte\Engine
239+
```php
240+
protected function beforeRender(): void
241+
{
217242
$latte = $this->template->getLatte();
218243
$latte->setMigrationWarnings();
219244
}
220245
```
221246

222-
Latte ve verzi 3 nabízí pokročilejší způsob a to vytvoření si [extension |latte:extending-latte#Latte Extension] pro každý webový projekt. Kusý příklad takové třídy:
247+
**Globálně pomocí Extension**
248+
249+
Předchozí způsoby jsou vhodné pro filtry a funkce, které potřebujete jen v konkrétním presenteru nebo komponentě, nikoliv v celé aplikaci. Pro celou aplikaci je nejvhodnější vytvořit si [extension |latte:extending-latte#Latte Extension]. Jde o třídu, která centralizuje všechna rozšíření Latte pro celý projekt. Kusý příklad:
223250

224251
```php
225252
namespace App\Presentation\Accessory;
@@ -251,18 +278,25 @@ final class LatteExtension extends Latte\Extension
251278
];
252279
}
253280

281+
private function filterTimeAgoInWords(DateTimeInterface $time): string
282+
{
283+
// ...
284+
}
285+
254286
// ...
255287
}
256288
```
257289

258-
Zaregistrujeme ji pomocí [konfigurace |configuration#Šablony Latte]:
290+
Extension zaregistrujeme pomocí [konfigurace |configuration#Šablony Latte]:
259291

260292
```neon
261293
latte:
262294
extensions:
263295
- App\Presentation\Accessory\LatteExtension
264296
```
265297

298+
Výhodou extension je, že lze využít dependency injection, mít přístup k modelové vrstvě aplikace a všechna rozšíření mít přehledně na jednom místě. Extension umožnuje definovat i vlastní značky, providery, průchody pro Latte kompilátor a další.
299+
266300

267301
Překládání
268302
----------

application/en/templates.texy

Lines changed: 59 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -111,16 +111,35 @@ Using `$this->setLayout(false)` or the `{layout none}` tag inside the template d
111111
The files where layout templates are looked up can be changed by overriding the [formatLayoutTemplateFiles() |api:Nette\Application\UI\Presenter::formatLayoutTemplateFiles()] method, which returns an array of possible file names.
112112

113113

114-
Variables in the Template
115-
-------------------------
114+
Template Variables
115+
------------------
116116

117-
Variables are passed to the template by writing them to `$this->template`, and then they are available in the template as local variables:
117+
Variables are passed to templates by writing them to `$this->template`. They then become available in the template as local variables:
118118

119119
```php
120120
$this->template->article = $this->articles->getById($id);
121121
```
122122

123-
This way, we can easily pass any variables to templates. However, when developing robust applications, it is often more useful to impose limitations. For example, by explicitly defining a list of variables that the template expects and their types. This allows PHP to perform type checking, the IDE to provide correct autocompletion, and static analysis to detect errors.
123+
124+
Default Variables
125+
-----------------
126+
127+
Presenters and components automatically pass several useful variables to templates:
128+
129+
- `$basePath` is the absolute URL path to the root directory (e.g., `/eshop`)
130+
- `$baseUrl` is the absolute URL to the root directory (e.g., `http://localhost/eshop`)
131+
- `$user` is an object [representing the user |security:authentication]
132+
- `$presenter` is the current presenter
133+
- `$control` is the current component or presenter
134+
- `$flashes` is an array of [messages |presenters#Flash Messages] sent by the `flashMessage()` function
135+
136+
If you use a custom template class, these variables are passed if you create a property for them.
137+
138+
139+
Type-Safe Variables
140+
-------------------
141+
142+
When developing robust applications, it's useful to explicitly define which variables the template expects and their types. This provides type checking in PHP, smart hints in your IDE, and enables static analysis to catch errors.
124143

125144
And how do we define such a list? Simply in the form of a class and its properties. We name it similarly to the presenter, but with `Template` at the end:
126145

@@ -169,21 +188,6 @@ public function renderDefault(): void
169188
```
170189

171190

172-
Default Variables
173-
-----------------
174-
175-
Presenters and components automatically pass several useful variables to templates:
176-
177-
- `$basePath` is the absolute URL path to the root directory (e.g., `/eshop`)
178-
- `$baseUrl` is the absolute URL to the root directory (e.g., `http://localhost/eshop`)
179-
- `$user` is an object [representing the user |security:authentication]
180-
- `$presenter` is the current presenter
181-
- `$control` is the current component or presenter
182-
- `$flashes` is an array of [messages |presenters#Flash Messages] sent by the `flashMessage()` function
183-
184-
If you use a custom template class, these variables are passed if you create a property for them.
185-
186-
187191
Creating Links
188192
--------------
189193

@@ -205,21 +209,44 @@ More information can be found in the chapter [Creating URL Links|creating-links]
205209
Custom Filters, Tags, etc.
206210
--------------------------
207211

208-
The Latte templating system can be extended with custom filters, functions, tags, etc. This can be done directly in the `render<View>` or `beforeRender()` method:
212+
The Latte templating system can be extended with custom filters, functions, tags, and other elements. There are three approaches available, ranging from quick ad-hoc solutions to architectural patterns for entire applications.
213+
214+
**Ad-hoc in Presenter Methods**
215+
216+
The quickest approach is adding filters or functions directly in presenter or component code. In presenters, the `beforeRender()` or `render<View>()` methods work well for this:
209217

210218
```php
211-
public function beforeRender(): void
219+
protected function beforeRender(): void
212220
{
213221
// adding a filter
214-
$this->template->addFilter('foo', /* ... */);
222+
$this->template->addFilter('money', fn($val) => '$' . number_format($val, 2));
223+
224+
// adding a function
225+
$this->template->addFunction('isWeekend', fn($date) => $date->format('N') >= 6);
226+
}
227+
```
228+
229+
In the template:
230+
231+
```latte
232+
<p>Price: {$price|money}</p>
233+
234+
{if isWeekend($now)} ... {/if}
235+
```
236+
237+
For more complex logic, you can configure the `Latte\Engine` object directly:
215238

216-
// or configure the Latte\Engine object directly
239+
```php
240+
protected function beforeRender(): void
241+
{
217242
$latte = $this->template->getLatte();
218243
$latte->setMigrationWarnings();
219244
}
220245
```
221246

222-
Latte version 3 offers a more advanced way by creating an [extension |latte:extending-latte#Latte Extension] for each web project. Here is a brief example of such a class:
247+
**Globally Using Extensions**
248+
249+
The previous approaches suit filters and functions needed only in specific presenters or components, not application-wide. For the entire application, creating an [extension |latte:extending-latte#Latte Extension] works best. This class centralizes all Latte extensions for your project. A brief example:
223250

224251
```php
225252
namespace App\Presentation\Accessory;
@@ -251,18 +278,25 @@ final class LatteExtension extends Latte\Extension
251278
];
252279
}
253280

281+
private function filterTimeAgoInWords(DateTimeInterface $time): string
282+
{
283+
// ...
284+
}
285+
254286
// ...
255287
}
256288
```
257289

258-
We register it using [configuration |configuration#Latte Templates]:
290+
Register the extension through [configuration |configuration#Latte Templates]:
259291

260292
```neon
261293
latte:
262294
extensions:
263295
- App\Presentation\Accessory\LatteExtension
264296
```
265297

298+
Extensions offer several advantages: dependency injection support, access to your application's model layer, and centralized management of all extensions. They also support custom tags, providers, compiler passes, and more.
299+
266300

267301
Translating
268302
-----------

0 commit comments

Comments
 (0)