渲染模板
直接获取或渲染模板
如基础中所述,你可使用$smarty->fetch()
或$smarty->display()
直接渲染模板。
<?php
use Smarty\Smarty;
$smarty = new Smarty();
$smarty->display('homepage.tpl');
// or
$output = $smarty->fetch('homepage.tpl');
当你使用display()
时,Smarty 会将模板渲染到标准输出流。fetch()
返回输出,而不是将其作为回声输出。
上面的示例使用简单文件名加载模板。Smarty 也支持 从资源加载模板。
创建模板对象
你还可以创建一个模板对象,可稍后先进行准备,然后进行渲染。这很有用,例如在计划重新使用多个模板时。
<?php
use Smarty\Smarty;
$smarty = new Smarty;
// create template object with its private variable scope
$tpl = $smarty->createTemplate('index.tpl');
// assign a variable (available only to this template)
$tpl->assign('title', 'My Homepage!');
// display the template
$tpl->display();
更多有关在模板中使用数据中分配变量的信息。
测试模板是否存在
你可以在尝试使用模板之前使用templateExists()
检查模板是否存在。
它接受在文件系统上指向模板的路径,或指定模板的资源字符串。
该示例使用$_GET['page']
来{include}
一个内容模板。如果模板不存在,则会显示一个错误页。首先,page_container.tpl
<html>
<head>
<title>{$title|escape}</title>
</head>
<body>
{* include middle content page *}
{include file=$content_template}
</body>
</html>
和 php 脚本