变量作用范围

你可以设置Smarty对象、通过createData()建立的对象、和createTemplate()建立的对象的作用范围。 这些对象可以连接使用。 模板内可以使用全部由对象的变量和它们链条上的父对象的变量。

默认模板通过 $smarty->display(…)$smarty->fetch(…)调用,可获取到Smarty对象范围的变量。

通过传递特定的数据或模板对象,你可以完全在模板内控制这些变量的可视范围。


Example 4.6. 变量范围的例子

  1.  
  2. // assign variable to Smarty object scope
  3. $smarty->assign('foo','smarty');
  4.  
  5. // assign variables to data object scope
  6. $data = $smarty->createData();
  7. $data->assign('foo','data');
  8. $data->assign('bar','bar-data');
  9.  
  10. // assign variables to other data object scope
  11. $data2 = $smarty->createData($data);
  12. $data2->assign('bar','bar-data2');
  13.  
  14. // assign variable to template object scope
  15. $tpl = $smarty->createTemplate('index.tpl');
  16. $tpl->assign('bar','bar-template');
  17.  
  18. // assign variable to template object scope with link to Smarty object
  19. $tpl2 = $smarty->createTemplate('index.tpl',$smarty);
  20. $tpl2->assign('bar','bar-template2');
  21.  
  22. // This display() does see $foo='smarty' from the $smarty object
  23. $smarty->display('index.tpl');
  24.  
  25. // This display() does see $foo='data' and $bar='bar-data' from the data object $data
  26. $smarty->display('index.tpl',$data);
  27.  
  28. // This display() does see $foo='data' from the data object $data
  29. // and $bar='bar-data2' from the data object $data2
  30. $smarty->display('index.tpl',$data2);
  31.  
  32. // This display() does see $bar='bar-template' from the template object $tpl
  33. $tpl->display(); // or $smarty->display($tpl);
  34.  
  35. // This display() does see $bar='bar-template2' from the template object $tpl2
  36. // and $foo='smarty' form the Smarty object $foo
  37. $tpl2->display(); // or $smarty->display($tpl2);
  38.  

参见assign(), createData()createTemplate().

原文: https://www.smarty.net/docs/zh_CN/language.variable.scopes.tpl