Include and Require
The include
and require
statements in Alapa enable you to modularize your templates by including external templates into your primary template at runtime. This approach helps maintain cleaner, more manageable code, especially in larger projects.
Key Differences
Include
- Purpose: Embeds another template into the current template.
- Behavior: Fails silently if the specified template is not found.
Require
- Purpose: Similar to
include
, but ensures that the template exists. - Behavior: Throws an exception if the specified template is missing, making it ideal for critical dependencies.
Syntax
Here are examples of how to use include
and require
:
untitled
{%
// Including templates
include 'my-template.html';
include 'my-template'; // without extensions
include ('my-template'); // enclosed in parentheses
// Requiring templates
require 'my-template.html';
require 'my-template';
require ('my-template');
%}
Advanced Usage
Including with Variables
You can pass variables to the included templates for dynamic content rendering.
untitled
{%
include 'header.html' with { title: "My Page Title", showNav: true };
%}
Conditionally Include Templates
Templates can be included based on conditions:
untitled
{%
if (user.isLoggedIn) {
include 'dashboard.html';
} else {
include 'login.html';
}
%}
Best Practices
- Use
require
for Mandatory Templates: Ensure critical templates are always loaded by usingrequire
instead ofinclude
. - Pass Context Explicitly: When including templates, pass necessary variables explicitly to avoid unintended side effects.
- Organize Templates: Group reusable templates (e.g., headers, footers) in a dedicated folder for better maintainability.
- Handle Missing Templates Gracefully: Use conditional logic to fallback to alternate templates if an optional template is missing.
Common Use Cases
-
Layout Composition: Include common layout elements such as headers, footers, or navigation bars:
untitled{%
include 'header.html';
include 'footer.html';
%} -
Dynamic Pages: Load specific content dynamically based on the context:
untitled
{%
if (page.type === 'article') {
include 'article.html';
} else {
include 'generic.html';
}
%}
-
Error Handling: Use
require
to ensure critical error templates are always included:untitled{%
try {
require 'error-handler.html';
} catch (error) {
console.error("Error template missing:", error);
}
%}