1

我正在尝试以一种平滑可维护的方式将模板的几个阶段融合在一起。我有一个外部页面,其中实例化了一个 smarty 对象,其中包括另一个实例化不同 smarty 对象的 php 页面。我的问题是是否有任何方法可以在外部实例中分配变量并在内部实例中访问它。

示意性地,我正在调用 page.php:

<?php
$tpl = new Smarty();
$tpl->assign("a","Richard");
$tpl->register_function('load_include', 'channel_load_include');
$tpl->display("outer_template.tpl");
function channel_load_include($params, &$smarty) {
    include(APP_DIR . $params["page"]);
}
?>

外部模板.tpl:

<div> {load_include page="/otherpage.php"} </div>

其他页面.php:

<?php
$tpl2=new Smarty();
$tpl2->assign("b","I");
$tpl2->display("inner_template.tpl");
?>

inner_template.tpl:

<span id="pretentiousReference"> "Richard loves {$a}, that is I am {$b}" </span>

我看到:“理查德爱,那就是我就是我”

有没有办法从内部实例访问外部实例的变量,或者我应该把它转储进去$_SESSION并用{php}标签拉出来?显然我的应用程序稍微复杂一点,但这暴露了我认为的核心问题。

4

1 回答 1

2

您可以构建 smarty / template / data 实例链,以使不同实例可以访问数据。

将 Smarty 实例分配为另一个实例的父级:

$outer = new Smarty();
$outer->assign('outer', 'hello');
$inner = new Smarty();
$inner->parent = $outer;
$inner->assign('inner', 'world');
$inner->display('eval:{$outer} {$inner}');

或者,您可以提取数据:

$data = new Smarty_Data();
$data->assign('outer', 'hello');
$outer = new Smarty();
$outer->parent = $data;
$inner = new Smarty();
$inner->parent = $data;
$inner->assign('inner', 'world');
$inner->display('eval:{$outer} {$inner}');

都输出“hello world”

于 2012-06-07T13:12:24.477 回答