Smarty include_php

include_php

 

Attribute Name Type Required Default 描述
file string Yes n/a The name of the php file to include
once boolean No true whether or not to include the php file more than once if included multiple times
assign string No n/a The name of the variable that the output of include_php will be assigned to

屬性 類型 是否必須 缺省值 描述
file string Yes n/a 待包含php檔的名稱
once boolean No true 如果待包含php檔已被包含是否仍然包含(類似php中的include_once函數)
assign string No n/a 該屬性指定一個變數保存待包含php檔的輸出

 

inluce_php 函數用於在範本中包含 php 腳本. 如果設置了安全模式,被包含的腳本必須位於 $trusted_dir 路徑下. include_php 函數必須設置 file 屬性,該屬性指明被包含 php 檔的路徑,可以是 $trusted_dir 的相對路徑,也可以是絕對路徑.

include_php 是解決範本部件化的好方法,它使得 php 代碼從範本檔中被分離出來. 舉個例子:假設有一個從資料庫中動態取出數據用於顯示站點導航的範本,你可以將得數據內容的 php 邏輯部分分離出來保存在一個單獨的檔夾下,並在範本開始的位置包含該 php 腳本. 那麼就可以在任何地方包含此範本而不用擔心之前資料庫資訊是否已被程式取出.

 

即使是在範本中多次地調用 php 檔,默認情況下它們只被包含一次. 你可以設置 once 屬性從而指明每次調用都重新包含該檔. 如果將 once 屬性設置為 false,每次調用該檔都將被重新包含.

 

如果設置了 assign 屬性,該屬性對應的變數名用於保存待包含 php 的輸出,這樣待包含 php 檔的輸出就不會直接顯示了。

 

在待包含 php 檔中可以通過 $this 訪問 smarty 對象.


Example 7-9. function include_php
例 7-9. include_php 函數演示

load_nav.php
-------------

<?php

	// load in variables from a mysql db and assign them to the template
	// 從mysql資料庫中取得數據,將數據賦給範本變數
	require_once("MySQL.class.php");
	$sql = new MySQL;
	$sql->query("select * from site_nav_sections order by name",SQL_ALL);
	$this->assign('sections',$sql->record);

?>


index.tpl
---------

{* absolute path, or relative to $trusted_dir *}
{* 絕對路徑或 $trusted_dir 的相對路徑 *}
{include_php file="/path/to/load_nav.php"}

{foreach item="curr_section" from=$sections}
	<a href="{$curr_section.url}">{$curr_section.name}</a><br>
{/foreach}


上一篇: Smarty include 下一篇: Smarty insert