跳到内容

基础

安装

有关安装说明,请参阅 入门部分

渲染模板

以下是你在 PHP 脚本中创建 Smarty 实例的方式

<?php

require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();

你现在有一个 Smarty 对象,你可以用它来渲染模板。

<?php

require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();

$smarty->display('string:The current smarty version is: {$smarty.version}.');
// or 
echo $smarty->fetch('string:The current smarty version is: {$smarty.version}.');

使用基于文件的模板

你可能希望将你的模板管理为文件。创建一个名为 'templates' 的子目录,然后配置 Smarty 来使用它

<?php

require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();

$smarty->setTemplateDir(__DIR__ . '/templates');

假设你有一个名为 'version.tpl' 的模板文件,存储在 'templates' 目录中,如下所示

<h1>Hi</h1>
The current smarty version is: {$smarty.version|escape}.

你现在可以使用以下方式渲染它

<?php

require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();

$smarty->setTemplateDir(__DIR__ . '/templates');
$smarty->display('version.tpl');

分配变量

一旦你在混合中添加变量,模板就会变得非常有用。

在 'templates' 目录中创建一个名为 'footer.tpl' 的模板,如下所示

<small>Copyright {$companyName|escape}</small>

现在给 'companyName' 变量赋值,并像这样渲染你的模板

<?php

require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();

$smarty->setTemplateDir(__DIR__ . '/templates');
$smarty->assign('companyName', 'AC & ME Corp.');
$smarty->display('footer.tpl');

运行此模板,你将看到以下内容

<small>Copyright AC &amp; ME Corp.</small>

请注意 转义修饰符 如何将 & 字符翻译成正确的 HTML 语法 &amp;。在 下一部分 中了解更多有关自动转义的信息。