鍍金池/ 教程/ PHP/ Smarty include_php
Smarty安裝
Smarty insert
Smarty 建立緩存
Smarty調(diào)試控制臺
Smarty if,elseif,else
Smarty include_php
Smarty多個緩存
Smarty方法
Smarty section,sectionelse
Smarty注釋代碼
Smarty屬性
Smarty緩沖處理函數(shù)
Smarty變量調(diào)節(jié)器
Smarty函數(shù)
Smarty組合修改器
Smarty雙引號里值的嵌入
Smarty預(yù)過濾器
Smarty foreach,foreachelse
Smarty include
Smarty Caching緩存
Smarty變量
Smarty assign用法
Smarty控制插件輸出緩沖
Smarty從配置文件讀取的變量
Smarty對象
Smarty literal
Smarty緩存集合
Smarty教程
Smarty display方法
Smarty自定義函數(shù)
Smarty配置文件
Smarty擴(kuò)展設(shè)置
Smarty數(shù)學(xué)運(yùn)算
Smarty輸出濾鏡
Smarty fetch方法

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函數(shù))
assign string No n/a 該屬性指定一個變量保存待包含php文件的輸出

 

inluce_php 函數(shù)用于在模板中包含 php 腳本. 如果設(shè)置了安全模式,被包含的腳本必須位于 $trusted_dir 路徑下. include_php 函數(shù)必須設(shè)置 file 屬性,該屬性指明被包含 php 文件的路徑,可以是 $trusted_dir 的相對路徑,也可以是絕對路徑.

include_php 是解決模板部件化的好方法,它使得 php 代碼從模板文件中被分離出來. 舉個例子:假設(shè)有一個從數(shù)據(jù)庫中動態(tài)取出數(shù)據(jù)用于顯示站點(diǎn)導(dǎo)航的模板,你可以將得數(shù)據(jù)內(nèi)容的 php 邏輯部分分離出來保存在一個單獨(dú)的文件夾下,并在模板開始的位置包含該 php 腳本. 那么就可以在任何地方包含此模板而不用擔(dān)心之前數(shù)據(jù)庫信息是否已被程序取出.

 

即使是在模板中多次地調(diào)用 php 文件,默認(rèn)情況下它們只被包含一次. 你可以設(shè)置 once 屬性從而指明每次調(diào)用都重新包含該文件. 如果將 once 屬性設(shè)置為 false,每次調(diào)用該文件都將被重新包含.

 

如果設(shè)置了 assign 屬性,該屬性對應(yīng)的變量名用于保存待包含 php 的輸出,這樣待包含 php 文件的輸出就不會直接顯示了。

 

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


Example 7-9. function include_php
例 7-9. include_php 函數(shù)演示

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

<?php

	// load in variables from a mysql db and assign them to the template
	// 從mysql數(shù)據(jù)庫中取得數(shù)據(jù),將數(shù)據(jù)賦給模板變量
	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}