Latte Functions

In addition to the common PHP functions, you can also use these in templates.

clamp clamps value to the range
divisibleBy checks if a variable is divisible by a number
even checks if the given number is even
first returns first element of array or character of string
last returns last element of array or character of string
odd checks if the given number is odd
slice extracts a slice of an array or a string

Usage

Functions are used in the same way as common PHP functions and can be used in all expressions:

<p>{clamp($num, 1, 100)}</p>

{if odd($num)} ... {/if}

Custom functions can be registered this way:

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

We use it in a template like this:

<p>{shortify($text)}</p>
<p>{shortify($text, 100)}</p>

Functions

clamp (int|float $value, int|float $min, int|float $max): int|float

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

{=clamp($level, 0, 255)}

See also filter clamp:

divisibleBy (int $value, int $by)bool

Checks if a variable is divisible by a number.

{if divisibleBy($num, 5)} ... {/if}

even (int $value): bool

Checks if the given number is even.

{if even($num)} ... {/if}

first (string|array $value)mixed

Returns the first element of array or character of string:

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

See also last, filter first.

last (string|array $value)mixed

Returns the last element of array or character of string:

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

See also first, filter last.

odd (int $value): bool

Checks if the given number is odd.

{if odd($num)} ... {/if}

slice (string|array $value, int $start, ?int $length=null, bool $preserveKeys=false): string|array

Extracts a slice of an array or a string.

{=slice('hello', 1, 2)}           {* outputs 'el' *}
{=slice(['a', 'b', 'c'], 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.

version: 3.0 2.x