setono/php-templates

一个极其简单却精彩的PHP模板系统

v1.2.0 2022-09-21 13:36 UTC

This package is auto-updated.

Last update: 2024-09-15 06:50:31 UTC


README

Latest Version Latest Unstable Version Software License Build Status Coverage Status Quality Score

在PHP世界中,我们拥有像TwigPlates这样的精彩模板引擎/系统。如果您需要像继承、扩展、内置助手等功能,您应该选择其中之一。

另一方面,如果您只想能够创建如下所示的PHP模板

<h1>Hello <?=$name?></h1>
<p>Today's date is <?=$date->format('d.m.Y')?></p>

那么这个库就是为您准备的。

安装

$ composer require setono/php-templates

用法

在这个例子中,我假设您的模板在这里: templates/php,并且您有一个如下所示的模板

<!-- templates/php/App/hello.php -->
<h1>Hello <?=$name?></h1>

这个模板的路径分为三部分:templates/php是添加到引擎的路径。 App是命名空间。 hello是模板名称。

在查看此模板的渲染时请记住这一点

<?php
// render.php

use Setono\PhpTemplates\Engine\Engine;

$engine = new Engine();
$engine->addPath('templates/php');

echo $engine->render('@App/hello', [
    'name' => 'John Doe',
]);

这将输出

<h1>Hello John Doe</h1>

覆盖模板

如果您想覆盖模板,这非常简单。让我们首先设置引擎

<?php
// override.php

use Setono\PhpTemplates\Engine\Engine;

$engine = new Engine();
$engine->addPath('vendor/namespace/src/templates/php'); // The path is added with a default priority of 0
$engine->addPath('templates/php', 10); // Here we set the priority higher than the vendor added path

这是我们要覆盖的模板

<!-- vendor/namespace/src/templates/php/ThirdPartyNamespace/hello.php -->
<h1>Hi <?=$name?>! This template is not rendered, since it is overridden</h1>

这是将要覆盖前面的模板

<!-- templates/php/ThirdPartyNamespace/hello.php -->
<h1>Hi <?=$name?>! This template is rendered, yeah!</h1>

注意我们通过添加与原始目录同名的新目录来覆盖模板。在这种情况下: ThirdPartyNamespace

<?php
echo $engine->render('@ThirdPartyNamespace/hello', [
    'name' => 'John Doe',
]);

这将输出

<h1>Hi John Doe! This template is rendered, yeah!</h1>