Smarty模版还可以包含其他文件,这里的其他文件包括其他静态HTML 文件以及其他模版文件。由于Smarty 模版可以接收来自PHP 代码的变量设定,一个模版文件还可以根据需要动态包含不同的文件。Smarty 模版包含文件的语法格式如下所示:
{include file=$filename variable=$value …}
其中,$filename 是要包含的文件的文件名,variable 和value 是用于替换被包含文件中关键字的变量设定。
一、以下代码是一个简单的包含文件的例子,其中test.htm 是模版文件,inc.htm 是被包含的一个静态HTML 文件。
- <?php
- require 'libs/Smarty.class.php'; //包含Smarty 类库文件
- $smarty = new Smarty; //创建一个新的Smarty 对象
- $smarty->display('test7.htm'); //显示页面
- ?>
模版文件的HTML 代码如下所示:
<html> <head> <title>Smarty Test</title> </head> <body> {include file="inc.htm"} </body> </html> |
被包含的文件inc.htm 代码如下所示。
This is a test!
运行结果如下所示:
This is a test!
可以看到,被包含的文件内容被显示出来了。
二、被包含的文件名还可以通过PHP 代码动态指定,下面将上面的示例代码如下:
PHP代码如下:
- <?php
- require 'libs/Smarty.class.php'; //包含Smarty 类库文件
- $smarty = new Smarty; //创建一个新的Smarty 对象
- $inc_name = "inc.htm";
- $smarty->assign("inc_name",$inc_name); //对模版中的变量赋值
- $smarty->display('test8.htm'); //显示页面
- ?>
模板文件如下:
<html> <head> <title>Smarty Test</title> </head> <body> {include file=$inc_name} </body> </html> |
运行结果与前面相同。
三、如果被包含的文件是模版,则需要使用调用该模版文件的模版来指定其中的变量。将前面的inc.htm改写如下:
{$sentence}
- <?php
- require 'libs/Smarty.class.php'; //包含Smarty 类库文件
- $smarty = new Smarty; //创建一个新的Smarty 对象
- $inc_name = "inc.htm";
- $sentence = "This is a test!";
- $smarty->assign("inc_name",$inc_name); //对模版中的变量赋值
- $smarty->assign("sentence",$sentence); //对模版中的变量赋值
- $smarty->display('test.htm'); //显示页面
- ?>
模版文件如下所示:
<html> <head> <title>Smarty Test</title> </head> <body> {include file=$inc_name sentence=$sentence} </body> </html> |
可以看到上面的例子将一个变量$sentence 从PHP 代码传入模版文件中,又通过模板文件传入inc.htm 中,实现了与前面例子相同的功能。
摘自:http://blog.163.com/star_verygood@yeah/blog/static/16792052720108248244597/
没有评论:
发表评论