Latte is a templating system used in the PHP framework Nette, which brings high performance, security, and ease of use. In this article, we will explore how to get started with Latte templates in your Nette projects, from basic setup to advanced templating techniques.
Basic Setup
To begin, you need to have the Nette framework installed in your project. This can be achieved using Composer, a dependency management tool in PHP. Upon installing Nette, the Latte templating engine is automatically included and does not require separate installation.
Creating Your First Template
Templates in Latte are typically stored in the templates
folder in your project. To create your first template, create a file with the .latte
extension in this folder. A simple template might look like this:
<!DOCTYPE html>
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>Welcome to My Page</h1>
<p>{$content}</p>
</body>
</html>
In this template, {$title}
and {$content}
are variables that will be replaced with actual values when the template is rendered.
Passing Variables to the Template
To pass values to the template, you need to define them in the presenter before rendering the template. In a Nette presenter, you can do this as follows:
public function renderDefault()
{
$this->template->title = 'My First Latte';
$this->template->content = 'This is the content of my page.';
}
Advanced Templating Techniques
Latte offers a range of advanced features for efficient templating, including conditional blocks, loops, layouts, macros, and filters, allowing you to create dynamic and flexible templates. For example, to display a list of items, you can use a foreach
loop:
<ul>
{foreach $items as $item}
<li>{$item}</li>
{/foreach}
</ul>
Latte templates in the Nette framework provide a powerful and secure environment for creating web pages and applications. With easy integration, high flexibility, and extensive support for modern templating techniques, Latte becomes the ideal choice for developers seeking an efficient and secure solution for their projects.