sy/template

PHP的简单模板引擎

2.2.9 2024-05-04 15:38 UTC

This package is auto-updated.

Last update: 2024-09-04 16:21:26 UTC


README

PHP简单模板引擎

安装

使用以下命令安装最新版本

composer require sy/template

基本用法

变量

<?php

use Sy\Template\Template;

// Create a template with variable slot
$template = new Template();
$template->setFile('mytemplate.tpl');

// Fill the variable slot
$template->setVar('NAME', 'World');

// Output render
echo $template->getRender();

模板文件 mytemplate.tpl 内容

Hello {NAME}

输出结果

Hello World

<?php

use Sy\Template\Template;

// Create a template with a block
$template = new Template();
$template->setFile('mytemplate.tpl');

// This variable will be overrided below
$template->setVar('NAME', 'Hello world');

// Fill the variable slot and repeat the block
foreach (['foo', 'bar', 'baz'] as $name) {
	$template->setVar('NAME', $name);
	$template->setBlock('MY_BLOCK');
}

// Output render
echo $template->getRender();

模板文件 mytemplate.tpl 内容

{NAME}
<!-- BEGIN MY_BLOCK -->
Hello {NAME}
<!-- END MY_BLOCK -->

输出结果

baz
Hello foo
Hello bar
Hello baz

块的隔离变量

<?php

use Sy\Template\Template;

// Create a template with a block
$template = new Template();
$template->setFile('mytemplate.tpl');

// This variable will not be overrided below because the block use isolated variables
$template->setVar('NAME', 'Hello world');

// Fill the variable slot and repeat the block
foreach (['foo', 'bar', 'baz'] as $name) {
	// Use isolated variables for this block
	$template->setBlock('MY_BLOCK', ['NAME' => $name]);
}

// Output render
echo $template->getRender();

模板文件 mytemplate.tpl 内容

{NAME}
<!-- BEGIN MY_BLOCK -->
Hello {NAME}
<!-- END MY_BLOCK -->

输出结果

Hello world
Hello foo
Hello bar
Hello baz

高级用法

ELSE块

您可以使用ELSE块为未设置的块设置默认输出

<?php

use Sy\Template\Template;

// Create a template with a block
$template = new Template();
$template->setFile('mytemplate.tpl');

// No setBlock here

// Output render
echo $template->getRender();

模板文件 mytemplate.tpl 内容

<!-- BEGIN MY_BLOCK -->
Hello {NAME}
<!-- ELSE MY_BLOCK -->
Block not set
<!-- END MY_BLOCK -->

输出结果

Block not set

槽位高级语法

1. 槽位名称周围的简单或双引号

您可以使用双引号或单引号围绕槽位名称

{"Hello"}, {'my name is'}...

如果这些槽位未设置,输出将是简单或双引号内的字符串

Hello, my name is...

2. 槽位默认值

您可以使用斜杠字符在槽位名称后设置默认值,以在未设置槽位时使用

Hello {NAME/John Doe}

如果槽位 NAME 未设置,输出将是

Hello John Doe

槽位默认行为

版本 1

槽位默认行为在版本 2 中已更改。在版本 1 中,未设置的槽位在输出时会被清除

Hello {NAME}

如果槽位 NAME 未设置,输出将是

Hello

版本 2

从版本 2 开始

Hello {NAME}

如果槽位 NAME 未设置,输出将是

Hello {NAME}

如何自动清除槽位

您可以使用“槽位默认值”功能来实现这一点。槽位将被替换为斜杠后的字符串,因此如果您在斜杠后放置空字符串,槽位将被替换为空字符串

Hello {NAME/}

如果槽位 NAME 未设置,输出将是

Hello