Smarty模板继承-传递变量?

3

首先,我正在使用最新版本的Smarty,并且一切都已经设置好了。

我的问题是,我有一个名为layout.tpl的整个网站的主模板,然后是每个页面的子模板,例如 home.tpl、about.tpl 等等...

index.php(用于 home 页面)

require('Smarty.class.php');
// --
$smarty = new Smarty;
$smarty->template_dir = 'C:/xampp/htdocs/EMP3/view/templates';
$smarty->config_dir = 'C:/xampp/htdocs/EMP3/view/config';
$smarty->cache_dir = 'C:/xampp/smarty/cache';
$smarty->compile_dir = 'C:/xampp/smarty/templates_c';
$smarty->display('home.tpl');

Home.tpl

{extends file="layout.tpl"}
{block name=title}Home{/block}
{block name=body}
<div>Sample</div>
{/block}

Layout.tpl

// Long html file which makes use of the blocks from home, about ect...

我的问题是,layout.tpl 中的 HTML 内容是根据用户是否为管理员或普通用户隐藏或显示的。我该如何将这些 PHP 值传递给 layout.tpl?通过 home.tpl 吗?有更好的方法实现这一点吗?
谢谢。
1个回答

1
我还没有使用过Smarty v3和Inheritance,只是根据你上面的示例代码,不过关于assign()怎么样?我知道当你有一个包含另一个文件的模板文件时,所有分配的变量仍然有效,同时能够在{include}语句中分配新的变量。

index.php(用于主页)

require('Smarty.class.php');
// --
$smarty = new Smarty;
$smarty->template_dir = 'C:/xampp/htdocs/EMP3/view/templates';
$smarty->config_dir = 'C:/xampp/htdocs/EMP3/view/config';
$smarty->cache_dir = 'C:/xampp/smarty/cache';
$smarty->compile_dir = 'C:/xampp/smarty/templates_c';

$smarty->assign('some_header', 'hello!');

$smarty->display('home.tpl');

Home.tpl(未更改)

Layout.tpl

<html>
    ...
    <h1>{$some_header}</h1>
    // Long html file which makes use of the blocks from home, about ect...
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接