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:
- Headers
- Footers
- Navigation menus
- Sidebars
- Authentication forms
By breaking your templates into partials, you can:
- Improve code organization and readability
- Enhance maintainability by isolating specific components
- Promote code reuse across different templates
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:
- One template without partials
- Another template that uses partials
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
Example #2: Template Using Partials
Best Practices
- Use partials for elements that are repeated across multiple pages or templates.
- Keep partials focused on a single responsibility or component.
- Use meaningful names for your partial files that reflect their content or purpose.
- Consider using partials for complex UI components that require their own logic and styling.