picea/docs/02-control-structure-functi...

43 lines
990 B
Markdown
Raw Permalink Normal View History

# Control structure - `function`
Sometimes comes a need to have a small subset of code which is gonna be used twice (or more)
in the same view. Instead of simply duplicating the code (with everything that can then go wrong if you ever need
to play with it later), you could create a `function`.
Functions are declared exactly like vanilla PHP.
**[PICEA]** So, using this code:
```html
{% use Psr\Http\Message\ServerRequestInterface %}
{% title "My generic title" %}
{% function printCustomTitle(ServerRequestInterface $request) : bool %}
{% if $request->getAttribute('lean.route')->name === 'home' %}
<h4 class="title">This is a custom title !</h4>
{% return true %}
{% endif %}
{% return false %}
{% endfunction %}
{% if ! printCustomTitle($request) %}
<h1>{{ title() }}</h1>
{% endif %}
```
**[HTML]** Would yield:
*page **is** 'home'*
```php
<h4>This is a custom title !</h4>
```
*page **is not** 'home'*
```php
<h4>My generic title</h4>
```