charm / tpl
一个极其简约的单文件模板引擎。使用PHP作为模板语言,但提供了类似Blade或Twig的模板继承功能。
0.0.4
2021-09-06 10:25 UTC
Requires
- charm/error: ^0
This package is auto-updated.
Last update: 2024-09-09 17:11:30 UTC
README
极其简约的模板引擎。对于那些不喜欢花费一天时间搭建框架和其他一切,只为制作小巧的工具或功能的人来说非常有用。与charm/orm配合使用,可实现简单的数据库抽象,与charm/router配合使用,可实现路由 - 但无需依赖。
我不建议PHP开发者再学习另一种模板语言。网络正朝着API方向发展,所以我决定编写一个尽可能简洁的模板引擎版本 - 而不会牺牲blade和twig的优点。
实际上,在项目大小方面,使用此模板引擎真的不应该有限制。源代码非常简单。挑战在于正确设置输出缓冲区,并获得优雅的结构。
以下为模板文件示例。这就是您使用模板引擎的方式
// TPL will proxy properties and methods from the $user instance in your template.
$template = new TPL('user/profile', $user);
echo $template->render(); // echo, send mail or whatever you want.
如果您真的很懒,这也行得通。我不推荐这样做,并可能移除此功能,因为它依赖于 __destruct() 方法。
<?php
require('vendor/autoload.php');
new Charm\TPL('hello-world', ['current_time' => gmdate('Y-m-d H:i:s')]);
安装 & 设置
安装包
composer require charm/tpl
为模板文件创建一个文件夹
mkdir templates
确保在尝试渲染模板之前,以下PHP代码已经运行
define APP_ROOT = '/var/www/html'; // Edit as appropriate
这就完成了!charm/tpl期望模板文件具有 .tpl.php
扩展名。
一个最小的主模板文件
我们将此文件放在 templates/skeleton/html5.tpl.php
。
<!DOCTYPE html>
<html>
<head>
<!-- $this->html() helps you NOT have to type htmlspecialchars($this->title, ENT_QUOTES) -->
<title><?=$this->html("title"); ?></title>
</head>
<body>
<main>
<?=$this->body; ?>
</main>
<sidebar>
<?=$this->sidebar; ?>
</sidebar>
<footer>
<?php foreach ($this->footerBlocks as $block) { ?>
<?=$block; ?>
<?php } ?>
</body>
</html>
当然,一切都是不受限制的PHP代码,所以您可以做任何想做的事情。
一个最小的子模板文件
此文件可以放在 templates/index.tpl.php
。
<?php $this->extend('skeleton/html5'); ?>
<h1>Body Part</h1>
<p>Whatever you output immediately after extend() will be used as the 'body' variable for the
parent template.</p>
<?php $this->part('sidebar'); ?>
<h2>Sidebar</h2>
<p>This goes into the 'sidebar' variable of the parent.</p>
<?php $this->add('footerBlocks'); ?>
<h3>Footer Block 1</h3>
<p>Using 'add()' makes 'footerBlocks' become an array.</p>
<?php $this->add('footerBlocks'); ?>
<?=$this->include('parts/footer-block', [ 'title' => 'Footer Block 2', 'text' => 'Some Text' ]); ?>
<?php $this->end(); ?>
一个最小的可重用模板部分
此文件可以放在 `templates/parts/footer-block.tpl.php'。
<div class="footer-block">
<h3><?=$this->html('title'); ?></h3>
<div><?=$this->html('text'); ?></div>
</div>