Default Latte Macros
Summary and description of all Latte template engine macros which are normally available.
Are you interested in taking a closer look at Latte syntax?
| Variable and expression printing | |
|---|---|
{$variable} |
prints an escaped variable |
{!$variable} |
prints a variable without escaping |
{expression} |
prints an escaped expression |
{!expression} |
prints an expression without escaping |
| Conditions | |
{if $cond} … {elseif $cond} … {else} … {/if}
if condition |
|
{ifset $var} … {elseifset $var} … {/ifset} if (isset()) condition |
|
{ifCurrent $link} … {/ifCurrent} |
special case of {if} for an active link |
| Loops | |
{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 |
| Variables | |
{var $foo = value} |
variable creation |
{default $foo = value} |
default value when variable isn't declared |
{capture $var} … {/capture} |
captures a section to a variable |
| Engine | |
{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 |
| Překlady | |
{_}Text{/_} |
translates a text |
{_expression} |
translates an expression and prints it with escaping |
{!_expression} |
translates an expression and prints it without 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 |
{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 |
| Links | |
n:href |
link in
<a> HTML elements |
{link Presenter:action} |
generates a link |
{plink Presenter:action} |
generates a link to a presenter |
| 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 |
n:input |
activates an HTML input element |
| AJAX | |
{snippet name} … {/snippet} |
a template snippet that can be sent by AJAX |
| Debugging | |
{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 exclamation mark:
<div class="article">
{!$content}
{!nl2br($notes)}
</div>
Alternatively you can use notations with equals sign
{=expression} and {!=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!
</script>
Conditions{if $cond} … {/if},
{ifCurrent $link}
Conditions behave exactly the same way as their PHP counterparts:
{if $stock}
In stock
{elseif $onWay}
On the way
{else}
Not available
{/if}
You can also use {ifset} macro which checks variable existence
and it 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:
{if}
<h1>Printing rows from the database</h1>
{foreach $database->table as $row} ... {/foreach}
{/if $row}
{ifCurrent destination} macro helps to determine that the
destination is the same as the current page. If the link points to the current
page we are able to style it differently for example. The trick is that when the
link is generated it is detected that the link points to the current page. The
result is retrieved from
$presenter->getCreatedRequest()->hasFlag(‘current’).
<!-- use cases -->
<a href="{link edit, 10}">edit</a>
<ul class="menu">
<li><a href="{link Default:default}">...</a></li>
<li><a href="{link}">...</a></li>
...
<li {ifCurrent Default:default}class="current"{/ifCurrent}><a href="{link Default:default}">...</a></li>
<!-- scope expanding -->
<li {ifCurrent Default:*}class="current"{/ifCurrent}><a href="{link Default:default}">...</a></li>
</ul>
<!-- negation -->
{ifCurrent Admin:login}{else}<a href="{link Admin:login}">Sign in!</a>{/ifCurrent}
Loops {foreach}, {for},
{while}
foreach, for and while loops behave
exactly the same as their PHP counterparts.
{foreach $result as $row}
<span>{$row->title}</span>
{/foreach}
{while $row = $result->fetch()}
<span>{$row->title}</span>
{/while}
{for $i = 0; $i < 10; $i++}
<span>Item #{$i}</span>
{/for}
Inside the for loop the $iterator variable is
initialized which holds important information about the current loop. Its API
features iteration counter and methods identifying odd, even, first and last
iteration:
isFirst()– is it the first iteration?isLast()– is it the last iteration?getCounter()– iteration counter, starts from 1isOdd()– 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}">
<td>{$row->name}</td>
<td>{$row->email}</td>
</tr>
{if $iterator->last}</table>{/if}
{/foreach}
{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, equivalent of {if
!$iterator->last} … {/if} notation (ie. not the last item) is
{sep} … {/sep} macro. Usually it marks the separator between the
items, for example comma. So, 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}
...
{/foreach}
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} works the same but sets the value only to the
nonexistent variables:
{default $lang = 'cs'}
Capturing to variables
{capture}
By using {capture} macro you can capture the output to a
variable:
{capture $var}
<ul>
<li>Hello World</li>
</ul>
{/capture}
<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:
{block|strip}
<ul>
<li>Hello World</li>
</ul>
{/block}
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 by the rules of the context. For example
{contentType xml} switches to the XML escaping mode, but
{contentType text} disables escaping completely.
If the parameter is complete MIME type the correct HTTP header is sent to the browser:
{contentType application/xml}
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>RSS feed</title>
<item>
...
</item>
</channel>
</rss>
Header {status}
Sends HTTP status code:
{status 500}
If the headers can't be sent an exception is thrown. You can prevent from
throwing it with optional sending by using the 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
</script>
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}.
n:class
There is one common problem we usually need to solve: when printing the data
from the database as <li> elements we don't know in advance
the number of items and we want every odd line to have alt CSS
class and the last one to have last CSS class. If the last line is
also odd we want both. And of course we don't want any empty attributes in the
code like <li class=" ">.
By using n:class macro the problem is rather trivial:
<ul>
{foreach $data as $item}
<li n:class="$iterator->odd ? alt, $iterator->last ? last">{$item}</li>
{/foreach}
</ul>
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
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.
<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. To work properly 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:
{_$variable}
For the textual parts you can use an alternative pair notation:
{_}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}
<h3>Menu</h3>
...
{/block}
We can nest the blocks and of course we can write them in
n:macro notation:
{block #sidebar}
<h3>Menu</h3>
...
<ul n:block="menulist">
...
</ul>
{/block}
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 including {include #block}
Block including is performed by {include} macro. To
differentiate from including a file we use the hash sign before the
block name:
{include #sidebar}
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:
{include #$block$name}
Blocks can also include themselves which is suitable when rendering a tree structured menu.
{block #menu}
<ul>
{foreach $menu as $item}
<li>{if is_array($item)}
{include #menu, menu => $item}
{else}
{$item}
{/if}</li>
{/foreach}
</ul>
{/block}
Instead of {include #menu, ...} we can write {include
#this, ...} where #this points to the current block.
Template expanding/inheritance
{layout}
Template expanding (also called inheritance) is powerful tool which enables us to follow easy and effective way of creation sometimes very complicated layouts without a need to repeat the code.
Lets have two simple pages. The first one:
<html>
<head>
<title>First page | My web</title>
</head>
<body>
<div id="sidebar">
<ul>...</ul>
</div>
<div id="content">
<p>Lorem Gypsum...</p>
</div>
</body>
</html>
and the second:
<html>
<head>
<title>Second page | My web</title>
</head>
<body>
<div id="sidebar">
<ul>...</ul>
</div>
<div id="content">
<p>Proin eu sem purus. Donec bibendum
vestibulum...</p>
</div>
</body>
</html>
The pages vary only by <title> and
<div#content> elements. So we'll create a layout where all
the common parts will be and also we'll create so called placeholders, which are
nothing more but blocks:
File @layout.latte:
<html>
<head>
<title>{block #title}{/block} | My web</title>
</head>
<body>
<div id="sidebar">
<ul>...</ul>
</div>
<div id="content">{block #content}{/block}</div>
</body>
</html>
In the actual templates we'll point to the layout by using the
{layout} macro, so we can minimize the template codes to have only
the two blocks:
{layout '@layout.latte'}
{block #title}First page{/block}
{block #content}<p>Lorem Gypsum...</p>{/block}
The other page will look similarly.
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:
$control->getComponent('cartControl')->render();
$control->getComponent('cartControl')->renderSmall();
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:small, $maxItems}
compiles to:
$control->getComponent('cartControl')->renderSmall($maxItems);
Forms {form}, {input},
{label}
Macros for rendering forms and their elements:
{form myForm}
<table>
<tr n:foreach="$form->controls as $name => $field">
<th>{label $name /}<th>
<td>{input $name}</td>
</tr>
</table>
{/form}
{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.
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 *}
