Trongate Website Homepage

Template Partials

Template partials in Trongate provide a way to modularize your template structure, enhancing code reusability and maintainability. This document explains the concept of partials and how to implement them effectively in your Trongate applications.

The use of partials in Trongate is optional. While they offer benefits in terms of code organization, you can create fully functional applications without using template partials.

Understanding Template Partials

A template partial is a reusable segment of a template that represents a specific section or functionality within a page. Common examples of partials include:

By breaking your templates into partials, you can:

Implementing Partials in Trongate

Directory Structure

By convention, partials are stored in the templates/views/partials directory. However, Trongate offers flexibility in partial location:

trongate_app/
├── templates/
│   ├── views/
│   │   ├── partials/
│   │   │   ├── header.php
│   │   │   ├── footer.php
│   │   │   └── ...
│   │   └── ...
│   └── ...
└── ...

While the 'partials' directory is recommended, you can store partials in the main 'views' folder of the templates module. To do so, adjust your partial calls accordingly.

Using Partials in Templates

To include a partial in your template, use the Template::partial() method:

<?= Template::partial('partials/header') ?>

<!-- Main content here -->

<?= Template::partial('partials/footer') ?>

Passing Data to Partials

You can pass data to partials using an associative array:

<?= Template::partial('partials/header', ['title' => 'Welcome to My Site']) ?>

In your partial file (e.g., header.php), you can then access this data:

<header>
    <h1><?= $title ?? 'Default Title' ?></h1>
</header>

Templates With and Without Partials

The following two screenshots demonstrate examples of two HTML templates:

Both of these approaches are valid, and the choice between using partials or not depends on your specific needs and preferences for code organization and reusability.

Example #1: Template Without Partials

Template without partials
A template without partials: All content in a single file

Example #2: Template Using Partials

Template using partials
A template using partials: Footer separated into a partial

Best Practices