mmdanziger
mmdanziger

Reputation: 4658

Nested SMARTY objects accessing variables across instances

I'm trying to mesh together several stages of templating in a smooth maintainable way. I have an outer page which has a smarty object instantiated and that includes another php page which instantiates a different smarty object. My question is if there is any way to assign a variable in the outer instance and have it accessible in the inner instance.

Schematically I'm calling 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"]);
}
?>

outer_template.tpl:

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

otherpage.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>

And I'm seeing: "Richard loves , that is I am I"

Is there a way to access the outer instance's variable from the inner instance or should I just dump it in $_SESSION and pull it with a {php} tag? Obviously my application is a tad more complicated but this exposes what I believe to be the core problem.

Upvotes: 1

Views: 752

Answers (1)

rodneyrehm
rodneyrehm

Reputation: 13557

You can build chains of smarty / template / data instances to make data accessible to different instances.

Assigning a Smarty instance as the parent of another one:

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

alternatively you could pull your data out:

$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}');

both output "hello world"

Upvotes: 2

Related Questions