You are browsing the unmaintained documentation for old Nette 2.1. See documentation for current Nette.

Default Latte Macros

Summary and description of all Latte template engine macros which are available by default.

Are you interested in taking a closer look at Latte syntax?

Variable and expression printing
{$variable} prints an escaped variable
{$variable|noescape} prints a variable without escaping
{expression} prints an escaped expression
{expression|noescape} prints an expression without escaping
{if $cond} … {elseif $cond} … {else} … {/if} if condition
{ifset $var} … {elseifset $var} … {/ifset} if (isset()) condition
{foreach $arr as $item} … {/foreach} foreach loop
{for expr; expr; expr} … {/for} for loop
{while expr} … {/while} while loop
{continueIf $cond} conditional jump to the next iteration
{breakIf $cond} conditional loop break
{first} … {/first} prints if first iteration
{last} … {/last} prints if last iteration
{sep} … {/sep} separator
{var $foo = value} variable creation
{default $foo = value} default value when variable isn't declared
{capture $var} … {/capture} captures a section to a variable
{include 'file.latte'} includes a template from other file
{cache $key} … {/cache} caches a template section
{? expression} evaluates an expression without printing it
{* comment text *} a comment (removed from evaluation)
{syntax mode} … {/syntax} switches the syntax at runtime
{use Class} loads new user-defined macros
{l} or {r} prints { and } characters, respectively
{contentType $type} switches the escaping mode and sends HTTP header
{status $code} sets an HTTP status code
HTML tag attributes
n:class smart class attribute
n:attr smart HTML attributes
{_}Text{/_} translates a text
{_expression} translates an expression and prints it with escaping
Blocks, layouts, template inheritance
{block block} block definition and immediate print out
{define block} block defintion for future use
{include block} inserts a block
{include mytemplate.latte} inserts a template
{includeblock 'file.latte'} loads blocks from external template
{layout 'file.latte'} specifies a layout file
{extends 'file.latte'} alias for {layout}
{ifset #block} … {/ifset} condition if block is defined
n:href link in <a> HTML elements
{link Presenter:action} generates a link
{plink Presenter:action} generates a link to a presenter
{ifCurrent $link} … {/ifCurrent} executes block if the given link is current
Controls and forms
{control loginForm} prints a component
{form formName} … {/form} prints a form element
{label fieldName} … {/label} prints a form input label
{input fieldName} prints a form input element
{inputError fieldName} prints error message for form input element
n:name activates an HTML input element
{snippet name} … {/snippet} a template snippet that can be sent by AJAX
{dump $variable} dumps variables to the Debugger Bar
{debugbreak $cond} sets breakpoint to the code

Variable and expression printing {expression}

With escaping: (eliminates the Cross Site Scripting vulnerability):

Full Name: {$name} {$surname}<br>
Age: {date('Y') - $birth}<br>

Without escaping by using the |noescape modifier (an exclamation mark was used in older Nette versions):

<div class="article">

Alternatively you can use notations with equals sign {=expression}.

With technology of Context-Aware Escaping it is also possible to use PHP variables inside the JavaScript safely:

$template->arr = array(1, 2, 3);
$template->name = 'Jim Beam';
<script type="text/javascript">
var pole = {$arr};
var name = {$name}; // strings are printed with quotes!

Conditions{if $cond} … {/if}

Conditions behave exactly the same way as their PHP counterparts:

{if $stock}
	In stock
{elseif $onWay}
	On the way
	Not available

You can also use {ifset} macro which checks variable existence and corresponds to the if (isset($var)) PHP code. {ifset} macro can check for block existence as well.

Expression in the {if} condition can be placed in the closing macro which is useful in situations when we don't know the expression at the time of opening the condition block:

	<h1>Printing rows from the database</h1>

	{foreach $database->table as $row} ... {/foreach}
{/if $row}

Loops {foreach}, {for}, {while}

foreach, for and while loops behave exactly the same as their PHP counterparts.

{foreach $result as $row}
{while $row = $result->fetch()}
{for $i = 0; $i < 10; $i++}
	<span>Item #{$i}</span>

Inside the foreach loop the $iterator variable is initialized. It holds important information about the current loop. Its API features iteration counter and methods identifying odd, even, first and last iteration:

  • isFirst() – is this the first iteration?
  • isLast() – is this the last iteration?
  • getCounter() – iteration counter, starts from 1
  • isOdd() – is this iteration odd?
  • isEven() – is this iteration even?

Object behind the $iterator variable has Nette\Object class characteristics, that's why you can write $iterator->first instead of $iterator->isFirst() and alike. For example:

{foreach $rows as $row}
	{if $iterator->first}<table>{/if}

	<tr id="row-{$iterator->counter}">

	{if $iterator->last}</table>{/if}

{if $iterator->first}<table>{/if} can be replaced with {first}<table>{/first}. Similarly, the condition with last can be also written as {last}</table>{/last}. Finally, the equivalent of {if !$iterator->last} … {/if} notation (ie. not the last item) is {sep} … {/sep} macro. Usually it marks the separator between items – comma, for example. This way the redundant right comma won't print:

{foreach $items as $item} {$item} {sep}, {/sep} {/foreach}

There are two special macros you can use inside the loop – {continueIf ?} and {breakIf ?} which jump to the next iteration and end the loop, respectively, if the conditions are met:

{foreach $rows as $row}
	{continueIf $row->parent == NULL}

Variable declaration {var} and {default}

We can declare variables directly in the template by using {var} macro:

{var $name = 'John Smith'}
{var $age = 27}

{* Multiple declaration *}
{var $name = 'John Smith', $age = 27}

Macro {default} does the same thing, except it only sets the value to nonexistent variables:

{default $lang = 'cs'}

Capturing to variables {capture}

By using {capture} macro you can capture the output to a variable:

{capture $var}
	<li>Hello World</li>

<p>Captured: {$var}</p>

If you want to capture the output only for a helper to be applied it is easier to use the helper on the {block} instead:

	<li>Hello World</li>

File including {include}

You can include other templates into the current template. The included file has access to the global variables of the current template. Additionally, we can also pass other variables listed in the macro:

{include 'basket.latte'}

{include 'menu.latte', level => 3, data => $menu}

In addition to including files the {include} macro is also used to include blocks.

Code evaluation {? expression}

This macro evaluates the code written inside but it does't print it.

Header {contentType}

Switches Context-Aware Escaping to the context determined by the parameter so that when printing, the variables are escaped using the rules of the context. For example {contentType xml} would switch to the XML escaping mode, meanwhile {contentType text} disables escaping completely.

If the parameter is a complete MIME type the correct HTTP header is sent to the browser:

{contentType application/xml}
<?xml version="1.0"?>
<rss version="2.0">
		<title>RSS feed</title>

Header {status}

Sends HTTP status code:

{status 500}

If the headers can't be sent an exception is thrown. You can prevent it from being thrown by using a question mark after the status code {status 500?}.

Syntax switching {syntax}

Macros don't have to be enclosed by simple braces only, we can also use other delimiters, even at runtime. That's the function of {syntax …} macro where we can use following parameters:

  • latte: {...}
  • double: {{...}}
  • asp: <%...%>
  • python: {% ... %} and {{ ... }}
  • off: completely disables macro evaluation

By using the n:macro notation we can disable Latte for a JavaScript block only:

<script n:syntax="off">
	var obj = {var: 123}; // this isn't a macro

Latte mode can easily be used in JavaScript, you just have to avoid the notation above by writing a space after the opening brace { var: 123} or by using quotes around the identifier {'var': 123}.


In a typical situation we could be trying to print an unknown amount of entries from the database as <li> elements and mark the last entry and every odd item with corresponding CSS classes for further styling. In case the last line is odd as well, we will require both classes, but we want to avoid empty classes like <li class=" ">.

By using n:class macro the problem is rather trivial:

	{foreach $data as $item}
	<li n:class="$iterator->odd ? alt, $iterator->last ? last">{$item}</li>

Or do you need to mark the current menu link with ‘current’ class?

<a href="#" n:class="$presenter->isLinkCurrent('Presenter:*') ? current">

Amazing, huh?


n:attr macro is able to generate any HTML attribute similarly to the n:class. It's mostly suitable in cases when we don't know which attributes we want to print and which not to.

<input type="checkbox" n:attr="value => $value, checked => $checked">

Depending on the values of the variables $value and $checked this will print:

<input type="checkbox">

{* $value = 'Hello' *}
<input type="checkbox" value="Hello">

{* $checked = TRUE *}
<input type="checkbox" value="Hello" checked>

Localization {_expression}

Macro which helps with automated translating in templates. For proper functionality a translator has to be set, see localization:

$template->setTranslator(new MyTranslator);

At this point every expression written in this macro will be automatically translated:


You can also use an alternative pair notation for chunks of text within a template:

{_}Text to be translated{/_}

Blocks {block} and {define}

Block selects a region of the template, for example to apply a helper (see example) or to name it and reinsert it elsewhere in the template.

{block sidebar}

We can nest the blocks and of course we can write them in n:macro notation:

{block sidebar}

	<ul n:block="menulist">

A block is immediately printed. In case we want to define the block only without printing it we can use {define} macro instead of {block}.

As for the name of the block it is allowed to specify it by a variable too: {block $var} … {/block}.

Every block can see the variables of its surroundings. But alternation of the value inside the block will be visible only in the block (and in nested blocks of course).

Existence of a block can by tested with {ifset #block} macro.

Block and template inclusion {include block} or {include 'mytemplate.latte'}

Block and template inclusion is performed using {include} macro.

{include sidebar}

Analogically for templates:

{include 'sidebar.latte'}

It is also possible to pass additional parameters:

{include sidebar, id => 123, name => $value}

We can include a block by specifying the block name stored in a variable as well (to differentiate from including a file we use the hash sign before the block name):

{include #$block$name}

Blocks can also include themselves which is suitable when rendering a tree structured menu.

{block menu}
	{foreach $menu as $item}
	<li>{if is_array($item)}
		{include menu, menu => $item}

Instead of {include menu, ...} we can write {include this, ...} where #this points to the current block.

If you need to add some code to the previously defined block (e.g. add a link to a new stylesheet), you don't need to redeclare and copy whole block. Use {include parent} instead.

{block styles}
	{include parent}
	<link href="" rel="stylesheet">

Template expansion/inheritance {layout}

Template expansion (also called inheritance) is a powerful tool which enables us to create even very complicated layouts effectively and with no code repetition.

Let's say we have two simple pages. The first one:

		<title>First page | My web</title>
		<div id="sidebar">

		<div id="content">
			<p>Lorem Gypsum...</p>

and the second:

		<title>Second page | My web</title>
		<div id="sidebar">

		<div id="content">
			<p>Proin eu sem purus. Donec bibendum

The pages vary only by <title> and <div#content> elements, so we'll create a layout file which contains all common parts and specifies placeholders, which are nothing more but blocks:

File @layout.latte:

		<title>{block title}{/block} | My web</title>
		<div id="sidebar">

		<div id="content">{block content}{/block}</div>

In the actual templates we'll point to the layout by using the {layout} macro, so we can minimize the template content by only defining the two blocks:

{layout '@layout.latte'}

{block title}First page{/block}

{block content}<p>Lorem Gypsum...</p>{/block}

The other page will look similar.

Also, there are no limits to the number of levels, there can be as many layers as you want.

Component rendering {control …}

{control} macro renders the presenter component. For better understanding it's good to know how the macro is compiled to PHP code.

{control cartControl}		renders whole cart on the page
{control cartControl:small}	renders small sidebar cart summary

This compiles to:


getComponent() method returns the cartControl component and then the render() or renderSmall() method, respectively, is called on it.

We can also add parameters which will be passed to the render method, for example:

{control cartControl, $maxItems, $showSummary}
{control cartControl, maxItems => 5, showSummary => true}
{control cartControl, [maxItems => 5, showSummary => true]}
{control cartControl:small, $maxItems, $showSummary}

compiles to:

$control->getComponent('cartControl')->render($maxItems, $showSummary);
$control->getComponent('cartControl')->render(array('maxItems' => 5, 'showSummary' => true));
$control->getComponent('cartControl')->render(array(array('maxItems' => 5, 'showSummary' => true)));
$control->getComponent('cartControl')->renderSmall($maxItems, $showSummary);

If anywhere in the parameter part => is used, all parameters will be wrapped with an array and passed as the first argument.

Rendering of sub-component:

{control cartControl-someForm}

compiles to:


Forms {form}, {input}, {inputError}{label}

Macros for rendering forms and their elements:

{form myForm}
<tr n:foreach="$form->controls as $name => $field">
	<th>{label $name /}<th>
	<td>{input $name}</td>
	<td n:ifcontent>{inputError $name}</td>

{input} macro renders any element including select boxes and textareas. {label} is optionally paired macro, ie. {label}Age{/label}, in that case the text is translated too. Macro {inputError} prints error message for form input.

Variable dumping {dump}

{dump $name} {* inspects the $name variable *}

{dump}       {* inspects all the defined variables *}

Break point {debugbreak}

Specifies the place where code execution will break. It is used for debugging purposes for the programmer to inspect the runtime environment and to ensure the code runs as expected. It supports Xdebug and PhpEd. Additionally, you can specify a condition when the code should break.

{debugbreak} {* breaks the program *}

{debugbreak $counter == 1}  {* breaks the program if the condition is met *}