View Package
PHP template engine with layouts and partials.
Installation
bash
composer require lighthouse/viewBasic Usage
php
use Lighthouse\View\View;
$view = new View(__DIR__ . '/views');
$html = $view->render('home', ['name' => 'John']);Rendering
php
// views/home.php
<h1>Hello, <?= $view->e($name) ?>!</h1>php
$html = $view->render('home', ['name' => 'John']);Escaping
Always escape output:
php
<?= $view->e($userInput) ?>For JSON in JavaScript:
php
<script>
const data = <?= $view->json($data) ?>;
</script>Layouts
Layout:
php
// views/layouts/main.php
<!DOCTYPE html>
<html>
<head>
<title><?= $view->yield('title', 'Default') ?></title>
</head>
<body>
<?= $view->yield('content') ?>
</body>
</html>Child view:
php
// views/home.php
<?php $view->extends('layouts.main'); ?>
<?php $view->section('title'); ?>
Home Page
<?php $view->endSection(); ?>
<?php $view->section('content'); ?>
<h1>Welcome!</h1>
<?php $view->endSection(); ?>Sections
php
// Define
<?php $view->section('sidebar'); ?>
<nav>...</nav>
<?php $view->endSection(); ?>
// Output
<?= $view->yield('sidebar') ?>
// With default
<?= $view->yield('sidebar', '<p>No sidebar</p>') ?>
// Check existence
<?php if ($view->hasSection('sidebar')): ?>
<?= $view->yield('sidebar') ?>
<?php endif; ?>Partials
php
// views/partials/card.php
<div class="card">
<h3><?= $view->e($title) ?></h3>
</div>php
// Include (echoes)
<?php $view->include('partials.card', ['title' => 'Hello']); ?>
// Partial (returns string)
<?= $view->partial('partials.card', ['title' => 'Hello']) ?>Shared Data
php
$view->share('appName', 'My App');
$view->share([
'year' => date('Y'),
'user' => $currentUser,
]);Access in any view:
php
<footer>© <?= $year ?> <?= $view->e($appName) ?></footer>Dot Notation
php
$view->render('users.index'); // views/users/index.php
$view->render('admin.users.edit'); // views/admin/users/edit.phpCheck Existence
php
if ($view->exists('emails.welcome')) {
$html = $view->render('emails.welcome');
}