這篇文章主要介紹了關於 如何在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}