PHP Luminova: Compose PHP Views with the Layout Engine
Compose reusable PHP layouts, capture named and nested sections, import partials, and substitute placeholders in rendered views.
Luminova’s PHP Layout Engine executes ordinary PHP templates. Use it to render a complete layout, extract individual sections to arrange in a page, or import reusable partials such as navigation and cards. A layout can access the options and exported helpers of the view that created it.
Start with the dashboard example, then reuse it to try nested sections, imports, placeholders, and defaults. Layout API reference
Enable Layouts in PHP Views
In app/Config/Template.php, select the default PHP engine and enable layouts. Edit the corresponding properties in your existing configuration class.
public string $templateEngine = 'default';
public bool $enablePhpTemplateLayout = true;
public bool $templateIsolation = false;A controller can render its view as usual.
public function home(): int
{
return $this->view('index', ['title' => 'Dashboard']);
}In resources/Views/index.php, access the layout through $this->layout. When templateIsolation is enabled, use $self->layout. See PHP Template View Isolation.
| Context | Layout access | Scope |
|---|---|---|
| Controller-rendered PHP view | $this->layout | $this is the View. |
| Controller-rendered PHP view with isolation enabled | $self->layout | $self is the framework’s view scope. |
A layout or partial executed by Layout | $this or $this->layout | Both refer to the current Layout instance. With isolation enabled, $self contains the attached View, if one was supplied. |
Inside a layout file, protected section methods are available because the file executes in the Layout’s class scope. A controller-rendered view uses public methods such as extend() and render().
Build a Page with Named Sections
Create resources/Views/layouts/dashboard.php. This file can serve as a complete HTML page or supply sections to another view.
<!doctype html>
<html lang="en">
<?php $this->layout->begin('head'); ?>
<head>
<meta charset="utf-8">
<title><?= htmlspecialchars($this->_title ?? 'Dashboard', ENT_QUOTES, 'UTF-8') ?></title>
</head>
<?php $this->layout->end('head'); ?>
<body>
<?php $this->layout->begin('content'); ?>
<main>
<h1>Dashboard</h1>
<p>{{ message }}</p>
<?php $this->layout->begin('actions'); ?>
<nav aria-label="Dashboard actions"><a href="/reports">Reports</a></nav>
<?php $this->layout->end('actions'); ?>
</main>
<?php $this->layout->end('content'); ?>
</body>
</html>Select the layout and arrange its sections in resources/Views/index.php.
<?php
$layout = $this->layout->template('layouts/dashboard');
$message = htmlspecialchars('Welcome to your dashboard.', ENT_QUOTES, 'UTF-8');
?>
<!doctype html>
<html lang="en">
<?= $layout->extend('head') ?>
<body>
<?= $layout->extend('content', ['message' => $message]) ?>
<?= $layout->extend('content.actions') ?>
</body>
</html>During section capture, content.actions is saved separately, so the returned content excludes the nested navigation. During a full render, the navigation stays where it appears in the template. Use dotted paths to distinguish nested sections with the same short name. A top-level section with an exact matching name takes precedence over a short alias.
To return the complete page instead, render the selected file in one call.
<?= $this->layout->template('layouts/dashboard')->render([
'message' => htmlspecialchars('Your reports are ready.', ENT_QUOTES, 'UTF-8'),
]) ?>Import Partials and Select Directories
Create resources/Views/layouts/card.php.
<article>
<h2><?= htmlspecialchars($heading ?? 'Overview', ENT_QUOTES, 'UTF-8') ?></h2>
</article>Render it from another layout or a controller-rendered view. The imported file has its own Layout instance and receives the options passed to its render call.
<?= $this->layout->import('layouts/card')->render(['heading' => 'Monthly reports']) ?>Import paths start at the current views root. They do not use the caller’s configured base folder. In an HMVC application, pass a module name to import from another module. The example resolves under app/Modules/Admin/Views/.
<?= $this->layout->import('layouts/card', 'Admin')->render(['heading' => 'Admin reports']) ?>To reuse a directory for multiple template selections, set a base and select the file relative to it.
<?php
use Luminova\Template\Engines\Layout;
$layout = Layout::of('layouts');
echo $layout->template('card')->render(['heading' => 'Monthly reports']);template() accepts a path with or without .php. It verifies that the resolved file is inside the configured base and views root. base() and module() affect subsequent selections, so call them before template(). Selecting a template clears the previous output, captured sections, and defaults. Use import() for nested rendering while a parent layout is executing.
Pass Variables and Substitute Placeholders
Each full render receives its own PHP variables from the supplied options. For section operations, the options from the first successful collection supply PHP variables to the template. Later calls can use different placeholder values without running the section template again.
<?php
$layout = $this->layout->template('layouts/dashboard');
echo $layout->extend('content', ['message' => 'First message']);
echo $layout->extend('content', ['message' => 'Second message']);In this example, {{ message }} changes on each call. A PHP expression such as <?= $message ?> inside a captured section is evaluated during the first collection. Select the template again or use a fresh instance when PHP expressions must run with different data.
For automatic placeholder substitution, values from the attached View take precedence over matching call options. If a placeholder has no matching value, it stays in the output. Substitution accepts scalar values, Stringable objects, and null. It inserts values literally, including dollar signs and backslashes. Escape untrusted data for its output context before passing it as a placeholder value.
Use autoDelimiter: false to keep placeholders in the returned output. To apply explicit replacements to a full layout, call resolve(), apply replacements, and cast the instance to a string. A subsequent render() executes the PHP file again.
<?php
$layout = $this->layout->template('layouts/dashboard')->resolve();
echo (string) $layout->replace('message', 'Your plan costs $10.');For captured sections, collect first with sections(autoDelimiter: false) before calling replace() or replaceAll(). Those methods update stored content. The automatic replacements supplied to extend() and sections() affect only the returned value.
Set Fallbacks and Adjust Sections
Register fallback content after selecting the template. An existing section with content takes precedence. An absent section or a section with an empty string uses the fallback.
<?php
$layout = $this->layout->template('layouts/dashboard')
->setDefault('footer', '<footer>Dashboard</footer>');
echo $layout->extend('footer');To provide the footer in the layout itself, add a named section to dashboard.php, just before </body>. The same view code now outputs the template footer because setDefault() only fills a missing or empty section.
<?php $this->layout->begin('footer'); ?>
<footer>Dashboard reports</footer>
<?php $this->layout->end('footer'); ?>The bundled Layout API has no setSection() method. If a view needs to choose the footer text on each call, put a placeholder in the section and supply its value when you extract it.
<?php $this->layout->begin('footer'); ?>
<footer>{{ footerText }}</footer>
<?php $this->layout->end('footer'); ?><?= $layout->extend('footer', ['footerText' => 'Monthly reports']) ?>
<?= $layout->extend('footer', ['footerText' => 'Yearly reports']) ?>Use prepend() and append() to add markup to captured sections. These calls collect sections if necessary and create the target section if it is missing. When a template needs options for its PHP expressions, collect with those options before applying these mutations.
<?php
$layout = $this->layout->template('layouts/dashboard');
$layout->sections(autoDelimiter: false);
$layout->prepend('content', '<p role="status">Reports are ready.</p>')
->append('content.actions', '<a href="/exports">Exports</a>');
echo $layout->extend('content', ['message' => 'Your reports are ready.']);
echo $layout->extend('content.actions');Section mutations affect output returned by extend() and sections(). A full render() executes the template independently.
Reuse a Layout Outside a Controller-Rendered View
Use the bundled CLI entry point or another script that has already loaded Luminova. Constructor arguments can also be passed to Layout::of() when you want a fresh instance.
<?php
use Luminova\Template\Engines\Layout;
$dashboard = new Layout();
$dashboard->base('layouts')->template('dashboard');
$sections = $dashboard->sections(['message' => 'Monthly reports']);
echo $sections['content'];
$card = Layout::of('layouts')->template('card');
echo $card->render(['heading' => 'Monthly reports']);
// Select a sibling template from the original views root.
$dashboard->base('')->template('layouts/card');
echo (string) $dashboard->resolve(['heading' => 'Yearly reports']);For HMVC, create the dashboard under app/Modules/Admin/Views/layouts/dashboard.php. Set the module before the base so the base directory is checked against that module’s views root.
<?php
use Luminova\Template\Engines\Layout;
$dashboard = Layout::of()
->module('Admin')
->base('layouts')
->template('dashboard');
echo $dashboard->render(['message' => 'Welcome to Admin.']);Compose Optional Sections and Update Several Placeholders
Create resources/Views/layouts/report.php with an optional summary and export link.
<?php $this->layout->begin('summary'); ?>
<h1>{{ heading }}</h1>
<p>{{ summary }}</p>
<?php $this->layout->end('summary'); ?>
<?php if ($showExport ?? false): ?>
<?php $this->layout->begin('export'); ?>
<a href="/reports/export">Export report</a>
<?php $this->layout->end('export'); ?>
<?php endif; ?>Collect with showExport before calling exists(), prepend(), or append(). Those calls can trigger the first collection, which determines which conditional sections are available. The public prepend and append calls both use the protected concat() helper.
<?php
$report = $this->layout->template('layouts/report');
$report->sections(['showExport' => true], autoDelimiter: false);
$report->replaceAll([
'heading' => 'Quarterly report',
'summary' => 'The export costs $10.',
], section: 'summary');
$report->prepend('summary', '<p>Prepared for the finance team</p>')
->append('summary', '<small>Figures are provisional.</small>');
echo $report->extend('summary');
if ($report->exists('export')) {
echo $report->extend('export');
}For full output, apply replaceAll() after resolve(). Casting or echoing the instance prints the updated stored output.
<?php
$report = $this->layout->template('layouts/report')->resolve(['showExport' => false]);
echo $report->replaceAll([
'heading' => 'Quarterly report',
'summary' => 'The report is ready for review.',
]);Reuse View Data and Helpers in a Partial
Create resources/Views/layouts/report-link.php. This example uses the attached View to read its title and generate a local link. The layout forwards the property read and method call through __get() and __call().
<a href="<?= htmlspecialchars($this->link('/reports'), ENT_QUOTES, 'UTF-8') ?>">
<?= htmlspecialchars($this->_title ?? 'Reports', ENT_QUOTES, 'UTF-8') ?>
</a>Render the partial from a controller-rendered view so the import inherits the attached View.
<?= $this->layout->import('layouts/report-link')->render() ?>With isolation enabled, call the import through $self->layout. The partial’s $this still refers to the layout.
Retry After Template Execution Fails
Create resources/Views/layouts/retry-example.php.
<?php
if ($simulateFailure ?? false) {
throw new LogicException('Intentional example failure.');
}
$this->layout->begin('result');
echo 'Report ready';
$this->layout->end('result');A failed collection clears its partial captures and allows another attempt on the same instance.
<?php
$layout = $this->layout->template('layouts/retry-example');
try {
$layout->sections(['simulateFailure' => true]);
} catch (LogicException) {
echo $layout->extend('result', ['simulateFailure' => false]);
}