PHP code example of migears / template
1. Go to this page and download the library: Download migears/template library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
migears / template example snippets
use MiGears\Template\Template;
$tpl = new Template(__DIR__ . '/views');
echo $tpl->render('user/profile', [
'name' => 'Alice',
'age' => 25,
]);
<!-- views/hello.php -->
<h1>Hello, <?= $this->e($name)
<!-- views/hello.tpl.php -->
<h1>Hello, ## $name ##!</h1>
<ul>
foreach ($items as $item):
// Escaped (safe for user input) — always use this by default
<?= $this->e($userInput)
<!-- views/layout/main.php — the layout -->
<!DOCTYPE html>
<html>
<head>
<title><?= $this->section('title', 'Default Title')
<!-- views/user/profile.php — child template -->
$this->extends('layout/main')
<!-- views/components/card.php -->
<div class="card">
<h3><?= $this->e($title)
<!-- In any template -->
<?= $this->component('components/card', [
'title' => 'Welcome',
'body' => 'Hello world',
])
$tpl = new Template(__DIR__ . '/views');
$tpl->addPath(__DIR__ . '/themes/dark'); // checked first
$rest = new MiRest(__DIR__ . '/resources', 'App\\Resources');
$rest->set('template', fn() => new Template(__DIR__ . '/views'));
// In a resource:
class Profile extends AbstractResource
{
public function GET(Request $request): Response
{
$tpl = $this->resolve('template');
$html = $tpl->render('user/profile', ['name' => 'Alice']);
return Response::html($html);
}
}
use MiGears\Template\Template;
$tpl = new Template(__DIR__ . '/views');
echo $tpl->render('user/profile', [
'name' => 'Alice',
'age' => 25,
]);
<!-- views/hello.php -->
<h1>你好,<?= $this->e($name)
<!-- views/hello.tpl.php -->
<h1>你好,## $name ##!</h1>
<ul>
foreach ($items as $item):
// 转义输出(用户输入安全)— 默认用这个
<?= $this->e($userInput)
<!-- views/layout/main.php — 布局 -->
<!DOCTYPE html>
<html>
<head>
<title><?= $this->section('title', '默认标题')
<!-- views/user/profile.php — 子模板 -->
$this->extends('layout/main')
<!-- views/components/card.php -->
<div class="card">
<h3><?= $this->e($title)
<!-- 在任意模板中 -->
<?= $this->component('components/card', [
'title' => '欢迎',
'body' => '你好,世界',
])
$tpl = new Template(__DIR__ . '/views');
$tpl->addPath(__DIR__ . '/themes/dark'); // 优先查找
$rest = new MiRest(__DIR__ . '/resources', 'App\\Resources');
$rest->set('template', fn() => new Template(__DIR__ . '/views'));
// 在资源类中:
class Profile extends AbstractResource
{
public function GET(Request $request): Response
{
$tpl = $this->resolve('template');
$html = $tpl->render('user/profile', ['name' => 'Alice']);
return Response::html($html);
}
}
bash
# 编译单个文件并输出生成的 PHP 代码到终端
php vendor/bin/compile.php views/hello.tpl.php
# 编译到指定文件
php vendor/bin/compile.php views/hello.tpl.php cache/hello.php
# 编译目录下所有 .tpl.php 文件
php vendor/bin/compile.php views/ cache/