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