PHPackages                             beastbytes/view-latte - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. beastbytes/view-latte

ActiveLibrary[Templating &amp; Views](/categories/templating)

beastbytes/view-latte
=====================

Yii Framework Latte Template Renderer

026PHP

Since Dec 7Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/beastbytes/view-latte)[ Packagist](https://packagist.org/packages/beastbytes/view-latte)[ RSS](/packages/beastbytes-view-latte/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

This package is an extension of the [Yii View Rendering Library](https://github.com/yiisoft/view/). This extension provides a `ViewRender` that allows use of the [Latte](https://latte.nette.org/) view template engine.

`Latte` has some advantages over `Twig` as a templating engine:

- The major advantage of Latte is that it is PHP (Twig is Python), this makes writing Latte templates simpler and debugging them (if you need to) a lot simpler.
- Use [PHP expressions in templates](https://latte.nette.org/en/syntax#toc-latte-understands-php)
- Better defence against XSS (Cross Site Scripting)
- Excellent plugin for PhpStorm that enables type hints, code completion, etc.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher.

Installation
------------

[](#installation)

Install the package using [Composer](https://getcomposer.org):

Either:

```
composer require beastbytes/view-latte
```

or add the following to the `require` section of your `composer.json`

```
"beastbytes/view-latte": "*"
```

Configuration
-------------

[](#configuration)

In order to register `Latte` as the renderer in `WebView`, the `beastbytes/view-latte` package must override the `yiisoft\view` package configuration. To do this, add `beastbytes/view-latte` to the `vendor-override-layer`option in `config-plugin-options`; this is either in the `extra` section of your root `composer.json`or in your external configuration file.

### composer.json

[](#composerjson)

```
"extra": {
    "config-plugin-options": {
        "vendor-override-layer": [
          "beastbytes/view-latte"
        ]
    },
    "config-plugin": {
        // ...
    }
}
```

### External Configuration File

[](#external-configuration-file)

```
'config-plugin-options' => [
    // other config-plugin-options
    'vendor-override-layer' => [
        'beastbytes/view-latte',
        // other vendor overrides
    ]
],
```

*Note:* if `beastbytes/view-latte` is the only vendor override, it can be specified as a string in both of the configuration formats.

### Params

[](#params)

The `beastbytes/view-latte` package supports the addition of user defined filters, functions, and extensions to `Latte`. Each filter and function is defined in its own class; extensions are packages.

To add them to `Latte` specify them in the `filterProviders`, `functionProviders`, and `extensions` keys of `beastbytes/view-latte` in the `params` array.

```
'beastbytes/view-latte' => [
    'filterProviders' => [
        new MyLatteFilter()
    ],
    'functionProviders' => [
        new MyLatteFunction()
    ],
    'extensions' => [
        new myLatteExtension()
    ]
],
```

See [User Defined Filters and Functions](#user-defined-filters-and-functions)for details on how to define filters and functions.

See [Creating an Extension](https://latte.nette.org/en/creating-extension) for details on how to create an extension.

Templates
---------

[](#templates)

As you would expect, all the variables defined when calling the view renderer's `render()` method in an action are available in the template, as are injected variables.

The Latte extension provides access to everything defined in the application container in all view templates and layouts.

#### Basic Layout &amp; View Templates

[](#basic-layout--view-templates)

**Note:** A major difference between `Latte` and `PHP` templates is the definition of `$this`.

- `$this` in Latte templates is the Latte template being rendered
- `$view` is the WebView instance

```
{varType string $content}
{varType Yiisoft\View\WebView $view}

{do $assetManager->register('App\Asset\AppAsset')}
{do $view->addCssFiles($assetManager->getCssFiles())}
{do $view->addCssStrings($assetManager->getCssStrings())}
{do $view->addJsFiles($assetManager->getJsFiles())}
{do $view->addJsStrings($assetManager->getJsStrings())}
{do $view->addJsVars($assetManager->getJsVars())}

{$view->beginPage()|noescape}

        {$view->getTitle()}
        {$view->head()|noescape}

        {$view->beginBody()|noescape}
        {include 'header.latte'}

            {$content|noescape}

        {include 'footer.latte'}
        {$view->endBody()|noescape}

{$view->endPage(true)|noescape}
```

And a view template will be:

```
{varType App\ApplicationParameters $applicationParameters}
{varType Yiisoft\View\WebView $view}

{do $view->setTitle($applicationParameters->getName())}

Hello!

Let's start something great with Yii3 &amp; Latte!

        Don't forget to check the Yii guide

        and the Latte documentation.

```

View-Latte Extensions
---------------------

[](#view-latte-extensions)

The `view-latte` package contains the following extensions:

### CacheExtension

[](#cacheextension)

**NOTE: CacheExtension is not implemented yet**

The `CacheExtension` allows caching of view fragments and dynamic content within cached fragments. The extension provides the `cache` and `dynamic` tags. It is enabled if the DI container contains a `Yiisoft\Cache\CacheInterface` implementation.

**NOTE:** Templates using caching *must* have the variable `$cache`, a concrete instance of `Yiisoft\Cache\CacheInterface`, defined

```
{varType Yiisoft\Cache\CacheInterface $cache}
```

#### {cache} Tag

[](#cache-tag)

The `cache` tag allows a template or part of a template to be cached. The tag has three parameters:

- ttl (int) – The TTL of the cached content in seconds. Default is `60`.
- dependency (Yiisoft\\Cache\\Dependency\\Dependency|null) – The dependency of the cached content. Default is `null`.
- beta (float) – The value for calculating the range that's used for "Probably early expiration". Default is `1.0`.

##### Examples

[](#examples)

###### Basic Usage

[](#basic-usage)

```
{cache}
    content to be cached
{/cache}
```

###### Set TTL

[](#set-ttl)

```
{cache 3600}
content to be cached
{/cache}
```

###### Set a Dependency

[](#set-a-dependency)

```
{cache 3600, new Yiisoft\Cache\Dependency\TagDependency('fragment-1')}
    content to be cached
{/cache}
...
{if $theAnswerToTheUltimateQuestionOfLife !== 42}
    {do Yiisoft\Cache\Dependency\TagDependency::invalidate('fragment-1')}
{/if}
```

#### {dynamic} Tag

[](#dynamic-tag)

The `dynamic` tag defines dynamic content within a `cache` tag. The tag has three parameters:

- contentGenerator (callable) – a callable that generates the dynamic content; it has the signature `function (array $parameters = []): string;`
- parameters (array) – parameters as key=&gt;value pairs passed to contentGenerator

```
{dynamic function (array $parameters = []): string {return $generatedContent}, ['a' => 1, 'b' => 2]}
```

There is no limit to the number of `dynamic` tags within a `cache` tag.

### UrlExtension

[](#urlextension)

The `UrlExtension` allows generation of URL using routes. The extension provides the `n:action`, `n:href`, and `n:src` n:attributes and `link` tag to generate URLs. It is enabled if the DI container contains a `Yiisoft\Router\UrlGeneratorInterface` implementation.

#### n:attributes

[](#nattributes)

The `n:action`, `n:href`, and `n:src` n:attributes are used to generate URLs as attributes in HTML tags; their parameters are the same as `Yiisoft\\Router\\UrlGeneratorInterface::generate().

##### n:action Attribute

[](#naction-attribute)

The `n:action` attribute is used to generate the action URL in `` tags.

```

    // Form controls

```

**Tip** The [form-latte extension](https://github.com/beastbytes/form-latte)integrates the Yii Framework Form package with view-latte.

##### n:href Attribute

[](#nhref-attribute)

The `n:href` attribute is used to generate links in `` tags;

```
Content
```

##### n:src Attribute

[](#nsrc-attribute)

The `n:src` attribute is used to generate URLs to the media source in media tags, e.g. ``;

```

```

#### {link} Tag

[](#link-tag)

The `{link}` tag is used to print a URL; its parameters are the same as `Yiisoft\\Router\\UrlGeneratorInterface::generate().

```
{link route/name, arguments, queryParameters}
```

### UseExtension

[](#useextension)

The `UseExtension` emulates PHP's `use` operator and allows writing cleaner templates. The extension provides provides the `use` tag. It is always enabled.

By default, Latte templates require the use of Fully Qualified CLass Names (FQCN); this can lead to cluttered templates. The `use` tag emulates PHP's `use` operator and allows templates to define the FQCN and optionally an alias, and refer to the *used* class by the alias or base class name.

#### Using Namespaced Classes in Latte

[](#using-namespaced-classes-in-latte)

The FQCN must be defined in a `use` tag before the base class name or alias is referenced in the template. The best way to ensure this is to place `use` tags at the start of the template.

The extension replaces the alias or base class name defined in the `use` tag with the FQCN in class instantation (`new`) statements and class constants during compilation; it *does not* import or alias the class.

#### Differences from PHP

[](#differences-from-php)

- There is no `as` clause when defining an alias
- Group `use` definitions are *not* supported.

#### {use} Tag

[](#use-tag)

```
{use Framework\Module\NamespacedClass}

The value is {(new NamespacedClass)->getValue()}
The constant is {NamespacedClass::CONSTANT}
```

#### {use} Tag with Alias

[](#use-tag-with-alias)

```
{use Framework\Module\Aliased\NamespacedClass AliasedClass}

The value is {(new AliasedClass)->getValue()}
The constant is {AliasedClass::CONSTANT}
```

#### Multiple {use} Tags

[](#multiple-use-tags)

```
{use Framework\Module\Aliased\NamespacedClass AliasedClass}
{use Framework\Module\NamespacedClass}

{varType int $arg}
{varType string $testString}

The value is {(new NamespacedClass($arg))->getValue()}
The constant is {NamespacedClass::CONSTANT}
{$testString|replace: AliasedClass::CONSTANT}
```

### YiiLatteExtension

[](#yiilatteextension)

The `YiiLatteExtension` allows access to any package in the DI container. The extension provides the `get` function which takes the id of the required package as a parameter. It is always enabled.

#### get() Function

[](#get-function)

```
{do $package = get('PackageId')}
```

Other Extensions
----------------

[](#other-extensions)

### TranslatorExtension

[](#translatorextension)

Latte's Translation Extension is enabled if the DI container contains a `Yiisoft\Translator\TranslatorInterface` implementation, allowing use of Latte's Translation [tags](https://latte.nette.org/en/tags#toc-translation)and [filter](https://latte.nette.org/en/filters#toc-translate) in templates.

### RawPhpExtension

[](#rawphpextension)

Latte's `RawPhpExtension` is *not* enabled by default. To enable it, add it to the `extensions` section of the `beastbytes/view-latte` in your configuration parameters:

```
return [
    'beastbytes/view-latte' => [
        'extensions' => [
            new \Latte\Essential\RawPhpExtension(),
            // Other extensions
        ],
        // Other view-latte configuration
    ],
]
```

User Defined Filters and Functions
----------------------------------

[](#user-defined-filters-and-functions)

The `view-latte` package supports the addition of user-defined filters and functions to the Latte Engine; see [Configuration -&gt; Params](#params) for details on how to specify them. This section details how to define them.

Each filter and/or function is defined in its own class. Filters must implement the FilterProviderinterface and functions the FunctionProviderinterface; both ***must*** implement the `__invoke()` method to provide their functionality.

### Example Filter

[](#example-filter)

```
