Home > Article > Backend Development > How to use php code in smarty template language
This article mainly introduces how to use php code in smarty template language. It has certain reference value. Now I share it with you. Friends in need can refer to it.
With the help of two smarty internal Build function.
1. The inluce_php function is used to include php scripts in the template. If the safe mode is set, the included script must be located in the $trusted_dir path. The include_php function must set the file attribute, which specifies the included php file. The path can be a relative path to $trusted_dir or an absolute path.
For example:
{include_php file="test.php"}
Example:
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. The php tag allows php to be directly embedded in the template Script, whether to process these statements depends on the setting of $php_handling. This statement usually does not need to be used, of course, if you know this feature very well or think it is necessary to use it, you can also use it.
For example:
{php}
echo "This is the function of php's built-in function";
{/php}
Example:
{php} // including a php script directly // from the template. include("/path/to/display_weather.php"); {/php}
Related recommendations:
smarty template engine configuration file data and retained data
How to use variables to adjust Smarty templates Device
Detailed explanation of how the Smarty template engine caches
The above is the detailed content of How to use php code in smarty template language. For more information, please follow other related articles on the PHP Chinese website!