您当前的位置:首页 > 分类 > 技术资讯 > Smarty > 正文

Smarty include,include_php

发布时间:2016-08-05 11:14:35      来源:51推一把
【摘要】Include标签用于在当前模板中包含其它模板。当前模板中的变量在被包含的模板中可用。必须指定 file 属性,该属性指明模板资源的位置.如果设置了assign属性,该属性对应的变量名用于保存待包含模板的输出,这样待包含模板的输出就不会直接显示了。
Include标签用于在当前模板中包含其它模板。
当前模板中的变量在被包含的模板中可用。必须指定 file 属性,该属性指明模板资源的位置.
如果设置了assign属性,该属性对应的变量名用于保存待包含模板的输出,这样待包含模板的输出就不会直接显示了。

#include样例
{include file="header.tpl"}
{* body of template goes here *}
{include file="footer.tpl"}


可以在属性中传递参数给待包含模板. 传递给待包含模板的参数只在待包含模板中可见. 如果传递的参数在待包含模板中有同名变量,那么该变量被

传递的参数替代.

#样例
{include file="header.tpl" title="Main Menu" table_bgcolor="#c0c0c0"}
{* body of template goes here *}
{include file="footer.tpl" logo="http://my.domain.com/logo.gif"}


包含 $template_dir 文件夹之外的模板请使用 模板资源 说明的格式.

{* absolute filepath *}
{include file="/usr/local/include/templates/header.tpl"}

{* absolute filepath (same thing) *}
{include file="file:/usr/local/include/templates/header.tpl"}

{* windows absolute filepath (MUST use "file:" prefix) *}
{include file="file:C:/www/pub/templates/header.tpl"}

{* include from template resource named "db" *}
{include file="db:header.tpl"}


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 对象.

#样例
load_nav.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}