这篇文章主要介绍了关于 如何在smarty模板语言中使用php代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
借助于两个smarty内建函数。
1. inluce_php 函数用于在模板中包含 php 脚本, 如果设置了安全模式,被包含的脚本必须位于 $trusted_dir 路径下. include_php 函数必须设置 file 属性,该属性指明被包含 php 文件的路径,可以是 $trusted_dir 的相对路径,也可以是绝对路径。
例如:
{include_php file=test.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}
2. php 标签允许在模板中直接嵌入 php 脚本,是否处理这些语句取决于$php_handling的设置. 该语句通常不需要使用,当然如果你非常了解此特性或认为必须要用,也可以使用。
例如:
{php}
echo "这个是php内建函数的作用";
{/php}
实例:
{php}
// including a php script directly
// from the template.
include("/path/to/display_weather.php");
{/php}
相关推荐:
smarty模板引擎之配置文件数据以及保留数据
smarty模板如何使用变量调节器
smarty模板引擎如何进行缓存的机制详解
以上就是如何在smarty模板语言中使用php代码的详细内容。