include_php function
include_php function:
include_php is a good way to solve the problem of template componentization, which separates the PHP code from the template file.
For example: Suppose there is a template that dynamically retrieves data from the database to display site navigation. You can get the data content in php Separate the logical part and save it in a separate folder,
and include the php script at the beginning of the template. Then you can include this template anywhere without worrying about the previous database Whether the information has been fetched by the program.
Even if the php file is called multiple times in the template, by default they are only included once. You can set the once attribute to indicate that each call The file will be re-included.
If the once attribute is set to false, the file will be re-included each time it is called. The assign attribute is set, and the variable name corresponding to this attribute is used to save the output of the PHP file to be included, so that the output of the PHP file to be included will not be displayed directly.
The smarty object can be accessed through $this in the php file to be included.
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}