Nette Documentation Preview

syntax
Latte Filters
*************

.[perex]
Filters are functions that change or format the data to a form we want. This is summary of the built-in filters which are available.

.[table-latte-filters]
|## String / array transformation
| `batch`      | [listing linear data in a table |#batch]
| `breakLines` | [Inserts HTML line breaks before all newlines |#breakLines]
| `bytes`      | [formats size in bytes |#bytes]
| `clamp`      | [clamps value to the range |#clamp]
| `dataStream` | [Data URI protocol conversion |#datastream]
| `date`       | [formats date |#date]
| `explode`    | [splits a string by the given delimiter |#explode]
| `first`      | [returns first element of array or character of string |#first]
| `implode`    | [joins an array to a string |#implode]
| `indent`     | [indents the text from left with number of tabs |#indent]
| `join`       | [joins an array to a string |#implode]
| `last`       | [returns last element of array or character of string |#last]
| `length`     | [returns length of a string or array |#length]
| `number`     | [formats number |#number]
| `padLeft`    | [completes the string to given length from left |#padLeft]
| `padRight`   | [completes the string to given length from right |#padRight]
| `random`     | [returns random element of array or character of string |#random]
| `repeat`     | [repeats the string |#repeat]
| `replace`    | [replaces all occurrences of the search string with the replacement |#replace]
| `replaceRE`  | [replaces all occurrences according to regular expression |#replaceRE]
| `reverse`    | [reverses an UTF‑8 string or array |#reverse]
| `slice`      | [extracts a slice of an array or a string |#slice]
| `sort`       | [sorts an array |#sort]
| `spaceless`  | [removes whitespace |#spaceless], similar to [spaceless |tags] tag
| `split`      | [splits a string by the given delimiter |#explode]
| `strip`      | [removes whitespace |#spaceless]
| `stripHtml`  | [removes HTML tags and converts HTML entities to text |#stripHtml]
| `substr`     | [returns part of the string |#substr]
| `trim`       | [strips whitespace from the string |#trim]
| `translate`  | [translation into other languages |#translate]
| `truncate`   | [shortens the length preserving whole words |#truncate]
| `webalize`   | [adjusts the UTF‑8 string to the shape used in the URL |#webalize]

.[table-latte-filters]
|## Letter casing
| `capitalize` | [lower case, the first letter of each word upper case |#capitalize]
| `firstUpper` | [makes the first letter upper case |#firstUpper]
| `lower`      | [makes a string lower case |#lower]
| `upper`      | [makes a string upper case |#upper]

.[table-latte-filters]
|## Rounding numbers
| `ceil`       | [rounds a number up to a given precision |#ceil]
| `floor`      | [rounds a number down to a given precision |#floor]
| `round`      | [rounds a number to a given precision |#round]

.[table-latte-filters]
|## Escaping
| `escapeUrl`  | [escapes parameter in URL |#escapeUrl]
| `noescape`   | [prints a variable without escaping |#noescape]
| `query`      | [generates a query string in the URL |#query]

There are also escaping filters for HTML (`escapeHtml` and `escapeHtmlComment`), XML (`escapeXml`), JavaScript (`escapeJs`), CSS (`escapeCss`) and iCalendar (`escapeICal`), which Latte uses itself thanks to [context-aware escaping |safety-first#Context-aware escaping] and you do not need to write them.

.[table-latte-filters]
|## Security
| `checkUrl`   | [sanitizes string for use inside href attribute |#checkUrl]
| `nocheck`    | [prevents automatic URL sanitization |#nocheck]

Latte the `src` and `href` attributes [checks automatically |safety-first#link checking], so you almost don't need to use the `checkUrl` filter.


.[note]
All built-in filters work with UTF‑8 encoded strings.


Usage
=====

Latte allows calling filters by using the pipe sign notation (preceding space is allowed):

```latte
<h1>{$heading|upper}</h1>
```

Filters can be chained, in that case they apply in order from left to right:

```latte
<h1>{$heading|lower|capitalize}</h1>
```

Parameters are put after the filter name separated by colon or comma:

```latte
<h1>{$heading|truncate:20,''}</h1>
```

Filters can be applied on expression:

```latte
{var $name = ($title|upper) . ($subtitle|lower)}</h1>
```

[Custom filters|extending-latte#filters] can be registered this way:

```php
$latte = new Latte\Engine;
$latte->addFilter('shortify', fn(string $s, int $len = 10) => mb_substr($s, 0, $len));
```

We use it in a template like this:

```latte
<p>{$text|shortify}</p>
<p>{$text|shortify:100}</p>
```


Filters
=======


batch(int length, mixed item): array .[filter]
----------------------------------------------
Filter that simplifies the listing of linear data in the form of a table. It returns an array of array with the given number of items. If you provide a second parameter this is used to fill up missing items on the last row.

```latte
{var $items = ['a', 'b', 'c', 'd', 'e']}
<table>
{foreach ($items|batch: 3, 'No item') as $row}
	<tr>
		{foreach $row as $column}
			<td>{$column}</td>
		{/foreach}
	</tr>
{/foreach}
</table>
```

Prints:

```latte
<table>
	<tr>
		<td>a</td>
		<td>b</td>
		<td>c</td>
	</tr>
	<tr>
		<td>d</td>
		<td>e</td>
		<td>No item</td>
	</tr>
</table>
```


breakLines .[filter]
--------------------
Inserts HTML line breaks before all newlines.

```latte
{var $s = "Text & with \n newline"}
{$s|breakLines}    {* outputs "Text &amp; with <br>\n newline" *}
```


bytes(int precision = 2) .[filter]
----------------------------------
Formats a size in bytes to human-readable form.

```latte
{$size|bytes}     0 B, 1.25 GB, …
{$size|bytes:0}   10 B, 1 GB, …
```


ceil(int precision = 0) .[filter]
---------------------------------
Rounds a number up to a given precision.

```latte
{=3.4|ceil}         {* outputs 4      *}
{=135.22|ceil:1}    {* outputs 135.3  *}
{=135.22|ceil:3}    {* outputs 135.22 *}
```

See also [#floor], [#round].


capitalize .[filter]
--------------------
Returns a title-cased version of the value. Words will start with uppercase letters, all remaining characters are lowercase. Requires PHP extension `mbstring`.

```latte
{='i like LATTE'|capitalize}  {* outputs 'I Like Latte' *}
```

See also [#firstUpper], [#lower], [#upper].


checkUrl .[filter]
------------------
Enforces URL sanitization. It checks if the variable contains a web URL (ie. HTTP/HTTPS protocol) and prevents the writing of links that may pose a security risk.

```latte
{var $link = 'javascript:window.close()'}
<a data-href={$link|checkUrl}>checked</a>
<a data-href={$link}>unchecked</a>
```

Prints:

```latte
<a data-href="">checked</a>
<a data-href="javascript:window.close()">unchecked</a>
```

See also [#nocheck].


clamp(int|float min, int|float max) .[filter]
---------------------------------------------
Returns value clamped to the inclusive range of min and max.

```latte
{$level|clamp: 0, 255}
```

Also exists as [function|functions#clamp].


dataStream(string mimetype = detect) .[filter]
----------------------------------------------
Converts the content to data URI scheme. It can be used to insert images into HTML or CSS without the need to link external files.

Lets have an image in a variable `$img = Image::fromFile('obrazek.gif')`, then

```latte
<img src={$img|dataStream}>
```

Prints for example:

```latte
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==">
```

.[caution]
Requires PHP extension `fileinfo`.


date(string format) .[filter]
-----------------------------
Returns a date in the given format using options of [php:strftime] or [php:date] PHP functions. Filter gets a date as a UNIX timestamp, a string or an object of `DateTime` type.

```latte
{$today|date:'%d.%m.%Y'}
{$today|date:'j. n. Y'}
```


escapeUrl .[filter]
-------------------
Escapes a variable to be used as a parameter in URL.

```latte
<a href="http://example.com/{$name|escapeUrl}">{$name}</a>
```

See also [#query].


explode(string separator = '') .[filter]
----------------------------------------
Splits a string by the given delimiter and returns an array of strings. Alias for `split`.

```latte
{='one,two,three'|explode:','}    {* returns ['one', 'two', 'three'] *}
```

If the delimiter is an empty string (default value), the input will be divided into individual characters:

```latte
{='123'|explode}                  {* returns ['1', '2', '3'] *}
```

You can use also alias `split`:

```latte
{='1,2,3'|split:','}              {* returns ['1', '2', '3'] *}
```

See also [#implode].


first .[filter]
---------------
Returns the first element of array or character of string:

```latte
{=[1, 2, 3, 4]|first}    {* outputs 1 *}
{='abcd'|first}          {* outputs 'a' *}
```

See also [#last], [#random].


floor(int precision = 0) .[filter]
----------------------------------
Rounds a number down to a given precision.

```latte
{=3.5|floor}        {* outputs 3      *}
{=135.79|floor:1}   {* outputs 135.7  *}
{=135.79|floor:3}   {* outputs 135.79 *}
```

See also [#ceil], [#round].


firstUpper .[filter]
--------------------
Converts a first letter of value to uppercase. Requires PHP extension `mbstring`.

```latte
{='the latte'|firstUpper}  {* outputs 'The latte' *}
```

See also [#capitalize], [#lower], [#upper].


implode(string glue = '') .[filter]
-----------------------------------
Return a string which is the concatenation of the strings in the array. Alias for `join`.

```latte
{=[1, 2, 3]|implode}      {* outputs '123' *}
{=[1, 2, 3]|implode:'|'}  {* outputs '1|2|3' *}
```

You can also use an alias `join`:

```latte
{=[1, 2, 3]|join}         {* outputs '123' *}
```


indent(int level = 1, string char = "\t") .[filter]
---------------------------------------------------
Indents a text from left by a given number of tabs or other characters which we specify in the second optional argument. Blank lines are not indented.

```latte
<div>
{block |indent}
<p>Hello</p>
{/block}
</div>
```

Prints:

```latte
<div>
	<p>Hello</p>
</div>
```


last .[filter]
--------------
Returns the last element of array or character of string:

```latte
{=[1, 2, 3, 4]|last}    {* outputs 4 *}
{='abcd'|last}          {* outputs 'd' *}
```

See also [#first], [#random].


length .[filter]
----------------
Returns length of a string or array.

- for strings, it will return length in UTF‑8 characters
- for arrays, it will return count of items
- for objects that implement the Countable interface, it will use the return value of the count()
- for objects that implement the IteratorAggregate interface, it will use the return value of the iterator_count()


```latte
{if ($users|length) > 10}
	...
{/if}
```


lower .[filter]
---------------
Converts a value to lowercase. Requires PHP extension `mbstring`.

```latte
{='LATTE'|lower}   {* outputs 'latte' *}
```

See also [#capitalize], [#firstUpper], [#upper].


nocheck .[filter]
-----------------
Prevents automatic URL sanitization. Latte [automatically checks|safety-first#Link checking] if the variable contains a web URL (ie. HTTP/HTTPS protocol) and prevents the writing of links that may pose a security risk.

If the link uses a different scheme, such as `javascript:` or `data:`, and you are sure of its contents, you can disable the check via `|nocheck`.

```latte
{var $link = 'javascript:window.close()'}

<a href={$link}>checked</a>
<a href={$link|nocheck}>unchecked</a>
```

Prints:

```latte
<a href="">checked</a>
<a href="javascript:window.close()">unchecked</a>
```

See also [#checkUrl].


noescape .[filter]
------------------
Disables automatic escaping.

```latte
{var $trustedHtmlString = '<b>hello</b>'}
Escaped: {$trustedHtmlString}
Unescaped: {$trustedHtmlString|noescape}
```

Prints:

```latte
Escaped: &lt;b&gt;hello&lt;/b&gt;
Unescaped: <b>hello</b>
```

.[warning]
Misuse of the `noescape` filter can lead to an XSS vulnerability! Never use it unless you are **absolutely sure** what you are doing and that the string you are printing comes from a trusted source.


number(int decimals = 0, string decPoint = '.', string thousandsSep = ',') .[filter]
------------------------------------------------------------------------------------
Formats a number to given number of decimal places. You can also specify a character of the decimal point and thousands separator.

```latte
{1234.20 |number}              1,234
{1234.20 |number:1}            1,234.2
{1234.20 |number:2}            1,234.20
{1234.20 |number:2, ',', ' '}  1 234,20
```


padLeft(int length, string pad = ' ') .[filter]
-----------------------------------------------
Pads a string to a certain length with another string from left.

```latte
{='hello'|padLeft: 10, '123'}  {* outputs '12312hello' *}
```


padRight(int length, string pad = ' ') .[filter]
------------------------------------------------
Pads a string to a certain length with another string from right.

```latte
{='hello'|padRight: 10, '123'}  {* outputs 'hello12312' *}
```


query  .[filter]
----------------
Dynamically generates a query string in the URL:

```latte
<a href="http://example.com/?{[name: 'John Doe', age: 43]|query}">click</a>
<a href="http://example.com/?search={$search|query}">search</a>
```

Prints:

```latte
<a href="http://example.com/?name=John+Doe&amp;age=43">click</a>
<a href="http://example.com/?search=Foo+Bar">search</a>
```

Keys with a value of `null` are omitted.

See also [#escapeUrl].


random .[filter]
----------------
Returns random element of array or character of string:

```latte
{=[1, 2, 3, 4]|random}    {* example output: 3 *}
{='abcd'|random}          {* example output: 'b' *}
```

See also [#first], [#last].


repeat(int count) .[filter]
---------------------------
Repeats the string x-times.

```latte
{='hello'|repeat: 3}  {* outputs 'hellohellohello' *}
```


replace(string|array search, string replace = '') .[filter]
-----------------------------------------------------------
Replaces all occurrences of the search string with the replacement string.

```latte
{='hello world'|replace: 'world', 'friend'}  {* outputs 'hello friend' *}
```

Multiple replacements can be made at once:

```latte
{='hello world'|replace: [h => l, l => h]}  {* outputs 'lehho worhd' *}
```


replaceRE(string pattern, string replace = '') .[filter]
--------------------------------------------------------
Replaces all occurrences according to regular expression.

```latte
{='hello world'|replaceRE: '/l.*/', 'l'}  {* outputs 'hel' *}
```


reverse .[filter]
-----------------
Reverses given string or array.

```latte
{var $s = 'Nette'}
{$s|reverse}    {* outputs 'etteN' *}
{var $a = ['N', 'e', 't', 't', 'e']}
{$a|reverse}    {* returns ['e', 't', 't', 'e', 'N'] *}
```


round(int precision = 0) .[filter]
----------------------------------
Rounds a number to a given precision.

```latte
{=3.4|round}        {* outputs 3      *}
{=3.5|round}        {* outputs 4      *}
{=135.79|round:1}   {* outputs 135.8  *}
{=135.79|round:3}   {* outputs 135.79 *}
```

See also [#ceil], [#floor].


slice(int start, int length = null, bool preserveKeys = false) .[filter]
------------------------------------------------------------------------
Extracts a slice of an array or a string.

```latte
{='hello'|slice: 1, 2}           {* outputs 'el' *}
{=['a', 'b', 'c']|slice: 1, 2}   {* outputs ['b', 'c'] *}
```

The slice filter works as the `array_slice` PHP function for arrays and `mb_substr` for strings with a fallback to `iconv_substr` in UTF‑8 mode.

If the start is non-negative, the sequence will start at that start in the variable. If start is negative, the sequence will start that far from the end of the variable.

If length is given and is positive, then the sequence will have up to that many elements in it. If the variable is shorter than the length, then only the available variable elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the variable. If it is omitted, then the sequence will have everything from offset up until the end of the variable.

Filter will reorder and reset the integer array keys by default. This behaviour can be changed by setting preserveKeys to true. String keys are always preserved, regardless of this parameter.


sort  .[filter]
---------------
Filter that sorts an array and maintain index association.

```latte
{foreach ($names|sort) as $name}
	...
{/foreach}
```

Array sorted in reverse order.

```latte
{foreach ($names|sort|reverse) as $name}
	...
{/foreach}
```

You can pass your own comparison function as a parameter:

```latte
{var $sorted = ($names|sort: fn($a, $b) => $b <=> $a)}
```


spaceless  .[filter]
--------------------
Removes unnecessary whitespace from the output. You can also use alias `strip`.

```latte
{block |spaceless}
	<ul>
		<li>Hello</li>
	</ul>
{/block}
```

Prints:

```latte
<ul> <li>Hello</li> </ul>
```


stripHtml .[filter]
-------------------
Converts HTML to plain text. That is, it removes HTML tags and converts HTML entities to text.

```latte
{='<p>one &lt; two</p>'|stripHtml}  {* outputs 'one < two' *}
```

The resulting plain text can naturally contain characters that represent HTML tags, for example `'&lt;p&gt;'|stripHtml` is converted to `<p>`. Never output the resulting text with `|noescape`, as this may lead to a security vulnerability.


substr(int offset, int length = null) .[filter]
-----------------------------------------------
Extracts a slice of a string. This filter has been replaced by a [#slice] filter.

```latte
{$string|substr: 1, 2}
```


translate(string message, ...args) .[filter]
--------------------------------------------
It translates expressions into other languages. To make the filter available, you need [set up translator|develop#TranslatorExtension]. You can also use the [tags for translation|tags#Translation].

```latte
<a href="basket">{='Baskter'|translate}</a>
<span>{$item|translate}</span>
```


trim(string charlist = " \t\n\r\0\x0B\u{A0}") .[filter]
-------------------------------------------------------
Strip leading and trailing characters, by default whitespace.

```latte
{='  I like Latte.  '|trim}    {* outputs 'I like Latte.' *}
{='  I like Latte.'|trim: '.'} {* outputs '  I like Latte' *}
```


truncate(int length, string append = '…') .[filter]
---------------------------------------------------
Shortens a string to the maximum given length but tries to preserve whole words. If the string is truncated it adds ellipsis at the end (this can be changed by the second parameter).

```latte
{var $title = 'Hello, how are you?'}
{$title|truncate:5}  {* Hell…                *}
{$title|truncate:17} {* Hello, how are…      *}
{$title|truncate:30} {* Hello, how are you?  *}
```


upper .[filter]
---------------
Converts a value to uppercase. Requires PHP extension `mbstring`.

```latte
{='latte'|upper}  {* outputs 'LATTE' *}
```

See also [#capitalize], [#firstUpper], [#lower].


webalize .[filter]
------------------
Converts to ASCII.

Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

```latte
{var $s = 'Our 10. product'}
{$s|webalize}    {* outputs 'our-10-product' *}
```

.[caution]
Requires package [nette/utils|utils:].

Latte Filters

Filters are functions that change or format the data to a form we want. This is summary of the built-in filters which are available.

String / array transformation
batch listing linear data in a table
breakLines Inserts HTML line breaks before all newlines
bytes formats size in bytes
clamp clamps value to the range
dataStream Data URI protocol conversion
date formats date
explode splits a string by the given delimiter
first returns first element of array or character of string
implode joins an array to a string
indent indents the text from left with number of tabs
join joins an array to a string
last returns last element of array or character of string
length returns length of a string or array
number formats number
padLeft completes the string to given length from left
padRight completes the string to given length from right
random returns random element of array or character of string
repeat repeats the string
replace replaces all occurrences of the search string with the replacement
replaceRE replaces all occurrences according to regular expression
reverse reverses an UTF‑8 string or array
slice extracts a slice of an array or a string
sort sorts an array
spaceless removes whitespace, similar to spaceless tag
split splits a string by the given delimiter
strip removes whitespace
stripHtml removes HTML tags and converts HTML entities to text
substr returns part of the string
trim strips whitespace from the string
translate translation into other languages
truncate shortens the length preserving whole words
webalize adjusts the UTF‑8 string to the shape used in the URL
Letter casing
capitalize lower case, the first letter of each word upper case
firstUpper makes the first letter upper case
lower makes a string lower case
upper makes a string upper case
Rounding numbers
ceil rounds a number up to a given precision
floor rounds a number down to a given precision
round rounds a number to a given precision
Escaping
escapeUrl escapes parameter in URL
noescape prints a variable without escaping
query generates a query string in the URL

There are also escaping filters for HTML (escapeHtml and escapeHtmlComment), XML (escapeXml), JavaScript (escapeJs), CSS (escapeCss) and iCalendar (escapeICal), which Latte uses itself thanks to context-aware escaping and you do not need to write them.

Security
checkUrl sanitizes string for use inside href attribute
nocheck prevents automatic URL sanitization

Latte the src and href attributes checks automatically, so you almost don't need to use the checkUrl filter.

All built-in filters work with UTF‑8 encoded strings.

Usage

Latte allows calling filters by using the pipe sign notation (preceding space is allowed):

<h1>{$heading|upper}</h1>

Filters can be chained, in that case they apply in order from left to right:

<h1>{$heading|lower|capitalize}</h1>

Parameters are put after the filter name separated by colon or comma:

<h1>{$heading|truncate:20,''}</h1>

Filters can be applied on expression:

{var $name = ($title|upper) . ($subtitle|lower)}</h1>

Custom filters can be registered this way:

$latte = new Latte\Engine;
$latte->addFilter('shortify', fn(string $s, int $len = 10) => mb_substr($s, 0, $len));

We use it in a template like this:

<p>{$text|shortify}</p>
<p>{$text|shortify:100}</p>

Filters

batch (int length, mixed item)array

Filter that simplifies the listing of linear data in the form of a table. It returns an array of array with the given number of items. If you provide a second parameter this is used to fill up missing items on the last row.

{var $items = ['a', 'b', 'c', 'd', 'e']}
<table>
{foreach ($items|batch: 3, 'No item') as $row}
	<tr>
		{foreach $row as $column}
			<td>{$column}</td>
		{/foreach}
	</tr>
{/foreach}
</table>

Prints:

<table>
	<tr>
		<td>a</td>
		<td>b</td>
		<td>c</td>
	</tr>
	<tr>
		<td>d</td>
		<td>e</td>
		<td>No item</td>
	</tr>
</table>

breakLines

Inserts HTML line breaks before all newlines.

{var $s = "Text & with \n newline"}
{$s|breakLines}    {* outputs "Text &amp; with <br>\n newline" *}

bytes (int precision = 2)

Formats a size in bytes to human-readable form.

{$size|bytes}     0 B, 1.25 GB, …
{$size|bytes:0}   10 B, 1 GB, …

ceil (int precision = 0)

Rounds a number up to a given precision.

{=3.4|ceil}         {* outputs 4      *}
{=135.22|ceil:1}    {* outputs 135.3  *}
{=135.22|ceil:3}    {* outputs 135.22 *}

See also floor, round.

capitalize

Returns a title-cased version of the value. Words will start with uppercase letters, all remaining characters are lowercase. Requires PHP extension mbstring.

{='i like LATTE'|capitalize}  {* outputs 'I Like Latte' *}

See also firstUpper, lower, upper.

checkUrl

Enforces URL sanitization. It checks if the variable contains a web URL (ie. HTTP/HTTPS protocol) and prevents the writing of links that may pose a security risk.

{var $link = 'javascript:window.close()'}
<a data-href={$link|checkUrl}>checked</a>
<a data-href={$link}>unchecked</a>

Prints:

<a data-href="">checked</a>
<a data-href="javascript:window.close()">unchecked</a>

See also nocheck.

clamp (int|float min, int|float max)

Returns value clamped to the inclusive range of min and max.

{$level|clamp: 0, 255}

Also exists as function.

dataStream (string mimetype = detect)

Converts the content to data URI scheme. It can be used to insert images into HTML or CSS without the need to link external files.

Lets have an image in a variable $img = Image::fromFile('obrazek.gif'), then

<img src={$img|dataStream}>

Prints for example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==">

Requires PHP extension fileinfo.

date (string format)

Returns a date in the given format using options of strftime or date PHP functions. Filter gets a date as a UNIX timestamp, a string or an object of DateTime type.

{$today|date:'%d.%m.%Y'}
{$today|date:'j. n. Y'}

escapeUrl

Escapes a variable to be used as a parameter in URL.

<a href="http://example.com/{$name|escapeUrl}">{$name}</a>

See also query.

explode (string separator = '')

Splits a string by the given delimiter and returns an array of strings. Alias for split.

{='one,two,three'|explode:','}    {* returns ['one', 'two', 'three'] *}

If the delimiter is an empty string (default value), the input will be divided into individual characters:

{='123'|explode}                  {* returns ['1', '2', '3'] *}

You can use also alias split:

{='1,2,3'|split:','}              {* returns ['1', '2', '3'] *}

See also implode.

first

Returns the first element of array or character of string:

{=[1, 2, 3, 4]|first}    {* outputs 1 *}
{='abcd'|first}          {* outputs 'a' *}

See also last, random.

floor (int precision = 0)

Rounds a number down to a given precision.

{=3.5|floor}        {* outputs 3      *}
{=135.79|floor:1}   {* outputs 135.7  *}
{=135.79|floor:3}   {* outputs 135.79 *}

See also ceil, round.

firstUpper

Converts a first letter of value to uppercase. Requires PHP extension mbstring.

{='the latte'|firstUpper}  {* outputs 'The latte' *}

See also capitalize, lower, upper.

implode (string glue = '')

Return a string which is the concatenation of the strings in the array. Alias for join.

{=[1, 2, 3]|implode}      {* outputs '123' *}
{=[1, 2, 3]|implode:'|'}  {* outputs '1|2|3' *}

You can also use an alias join:

{=[1, 2, 3]|join}         {* outputs '123' *}

indent (int level = 1, string char = "\t")

Indents a text from left by a given number of tabs or other characters which we specify in the second optional argument. Blank lines are not indented.

<div>
{block |indent}
<p>Hello</p>
{/block}
</div>

Prints:

<div>
	<p>Hello</p>
</div>

last

Returns the last element of array or character of string:

{=[1, 2, 3, 4]|last}    {* outputs 4 *}
{='abcd'|last}          {* outputs 'd' *}

See also first, random.

length

Returns length of a string or array.

  • for strings, it will return length in UTF‑8 characters
  • for arrays, it will return count of items
  • for objects that implement the Countable interface, it will use the return value of the count()
  • for objects that implement the IteratorAggregate interface, it will use the return value of the iterator_count()
{if ($users|length) > 10}
	...
{/if}

lower

Converts a value to lowercase. Requires PHP extension mbstring.

{='LATTE'|lower}   {* outputs 'latte' *}

See also capitalize, firstUpper, upper.

nocheck

Prevents automatic URL sanitization. Latte automatically checks if the variable contains a web URL (ie. HTTP/HTTPS protocol) and prevents the writing of links that may pose a security risk.

If the link uses a different scheme, such as javascript: or data:, and you are sure of its contents, you can disable the check via |nocheck.

{var $link = 'javascript:window.close()'}

<a href={$link}>checked</a>
<a href={$link|nocheck}>unchecked</a>

Prints:

<a href="">checked</a>
<a href="javascript:window.close()">unchecked</a>

See also checkUrl.

noescape

Disables automatic escaping.

{var $trustedHtmlString = '<b>hello</b>'}
Escaped: {$trustedHtmlString}
Unescaped: {$trustedHtmlString|noescape}

Prints:

Escaped: &lt;b&gt;hello&lt;/b&gt;
Unescaped: <b>hello</b>

Misuse of the noescape filter can lead to an XSS vulnerability! Never use it unless you are absolutely sure what you are doing and that the string you are printing comes from a trusted source.

number (int decimals = 0, string decPoint = '.', string thousandsSep = ',')

Formats a number to given number of decimal places. You can also specify a character of the decimal point and thousands separator.

{1234.20 |number}              1,234
{1234.20 |number:1}            1,234.2
{1234.20 |number:2}            1,234.20
{1234.20 |number:2, ',', ' '}  1 234,20

padLeft (int length, string pad = ' ')

Pads a string to a certain length with another string from left.

{='hello'|padLeft: 10, '123'}  {* outputs '12312hello' *}

padRight (int length, string pad = ' ')

Pads a string to a certain length with another string from right.

{='hello'|padRight: 10, '123'}  {* outputs 'hello12312' *}

query

Dynamically generates a query string in the URL:

<a href="http://example.com/?{[name: 'John Doe', age: 43]|query}">click</a>
<a href="http://example.com/?search={$search|query}">search</a>

Prints:

<a href="http://example.com/?name=John+Doe&amp;age=43">click</a>
<a href="http://example.com/?search=Foo+Bar">search</a>

Keys with a value of null are omitted.

See also escapeUrl.

random

Returns random element of array or character of string:

{=[1, 2, 3, 4]|random}    {* example output: 3 *}
{='abcd'|random}          {* example output: 'b' *}

See also first, last.

repeat (int count)

Repeats the string x-times.

{='hello'|repeat: 3}  {* outputs 'hellohellohello' *}

replace (string|array search, string replace = '')

Replaces all occurrences of the search string with the replacement string.

{='hello world'|replace: 'world', 'friend'}  {* outputs 'hello friend' *}

Multiple replacements can be made at once:

{='hello world'|replace: [h => l, l => h]}  {* outputs 'lehho worhd' *}

replaceRE (string pattern, string replace = '')

Replaces all occurrences according to regular expression.

{='hello world'|replaceRE: '/l.*/', 'l'}  {* outputs 'hel' *}

reverse

Reverses given string or array.

{var $s = 'Nette'}
{$s|reverse}    {* outputs 'etteN' *}
{var $a = ['N', 'e', 't', 't', 'e']}
{$a|reverse}    {* returns ['e', 't', 't', 'e', 'N'] *}

round (int precision = 0)

Rounds a number to a given precision.

{=3.4|round}        {* outputs 3      *}
{=3.5|round}        {* outputs 4      *}
{=135.79|round:1}   {* outputs 135.8  *}
{=135.79|round:3}   {* outputs 135.79 *}

See also ceil, floor.

slice (int start, int length = null, bool preserveKeys = false)

Extracts a slice of an array or a string.

{='hello'|slice: 1, 2}           {* outputs 'el' *}
{=['a', 'b', 'c']|slice: 1, 2}   {* outputs ['b', 'c'] *}

The slice filter works as the array_slice PHP function for arrays and mb_substr for strings with a fallback to iconv_substr in UTF‑8 mode.

If the start is non-negative, the sequence will start at that start in the variable. If start is negative, the sequence will start that far from the end of the variable.

If length is given and is positive, then the sequence will have up to that many elements in it. If the variable is shorter than the length, then only the available variable elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the variable. If it is omitted, then the sequence will have everything from offset up until the end of the variable.

Filter will reorder and reset the integer array keys by default. This behaviour can be changed by setting preserveKeys to true. String keys are always preserved, regardless of this parameter.

sort

Filter that sorts an array and maintain index association.

{foreach ($names|sort) as $name}
	...
{/foreach}

Array sorted in reverse order.

{foreach ($names|sort|reverse) as $name}
	...
{/foreach}

You can pass your own comparison function as a parameter:

{var $sorted = ($names|sort: fn($a, $b) => $b <=> $a)}

spaceless

Removes unnecessary whitespace from the output. You can also use alias strip.

{block |spaceless}
	<ul>
		<li>Hello</li>
	</ul>
{/block}

Prints:

<ul> <li>Hello</li> </ul>

stripHtml

Converts HTML to plain text. That is, it removes HTML tags and converts HTML entities to text.

{='<p>one &lt; two</p>'|stripHtml}  {* outputs 'one < two' *}

The resulting plain text can naturally contain characters that represent HTML tags, for example '&lt;p&gt;'|stripHtml is converted to <p>. Never output the resulting text with |noescape, as this may lead to a security vulnerability.

substr (int offset, int length = null)

Extracts a slice of a string. This filter has been replaced by a slice filter.

{$string|substr: 1, 2}

translate (string message, …args)

It translates expressions into other languages. To make the filter available, you need set up translator. You can also use the tags for translation.

<a href="basket">{='Baskter'|translate}</a>
<span>{$item|translate}</span>

trim (string charlist = " \t\n\r\0\x0B\u{A0}")

Strip leading and trailing characters, by default whitespace.

{='  I like Latte.  '|trim}    {* outputs 'I like Latte.' *}
{='  I like Latte.'|trim: '.'} {* outputs '  I like Latte' *}

truncate (int length, string append = '…')

Shortens a string to the maximum given length but tries to preserve whole words. If the string is truncated it adds ellipsis at the end (this can be changed by the second parameter).

{var $title = 'Hello, how are you?'}
{$title|truncate:5}  {* Hell…                *}
{$title|truncate:17} {* Hello, how are…      *}
{$title|truncate:30} {* Hello, how are you?  *}

upper

Converts a value to uppercase. Requires PHP extension mbstring.

{='latte'|upper}  {* outputs 'LATTE' *}

See also capitalize, firstUpper, lower.

webalize

Converts to ASCII.

Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

{var $s = 'Our 10. product'}
{$s|webalize}    {* outputs 'our-10-product' *}

Requires package nette/utils.