2012-06-07 33 views
1

我試圖以光滑可維護的方式將模板的幾個階段網格化在一起。我有一個外部頁面,其中有一個聰明的對象實例化,幷包含另一個實例化不同的聰明對象的PHP頁面。我的問題是,如果有任何方式在外部實例中分配一個變量並讓它在內部實例中可訪問。跨實例訪問變量的嵌套SMARTY對象

示意我打電話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> 

而且我看到:「理查德愛,那就是我是我」

有沒有辦法從內部實例訪問外實例的變量的方式或者我應該只轉儲它$_SESSION並用拉{php}標籤?很明顯,我的應用程序有點複雜,但是這暴露了我認爲是核心問題。

+0

不知道如果它符合你的需求,但你可能有幾個階段的聰明渲染,如{$ a}和<@[email protected]> –

+0

另一個想法是使用{include}插件來包含一個子模板而不是一個子php; http://www.smarty.net/docsv2/en/language.function.include.tpl;他們共享分配變量 –

+0

@JeromeWAGNER,這將在我在這裏顯示的簡單情況下工作,但會爲我的真實應用程序需要不切實際的大型重寫。我需要一個解決方案,使整個層次結構保持完好。 – mmdanziger

回答

2

您可以構建smarty /模板/數據實例鏈以使數據可以訪問不同的實例。

分配一個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」