2013年1月10日星期四

【转】Smarty载入外部文件方法.

      Smarty模版还可以包含其他文件,这里的其他文件包括其他静态HTML 文件以及其他模版文件。由于Smarty 模版可以接收来自PHP 代码的变量设定,一个模版文件还可以根据需要动态包含不同的文件。Smarty 模版包含文件的语法格式如下所示:


{include file=$filename variable=$value …}


其中,$filename 是要包含的文件的文件名,variable 和value 是用于替换被包含文件中关键字的变量设定。

一、以下代码是一个简单的包含文件的例子,其中test.htm 是模版文件,inc.htm 是被包含的一个静态HTML 文件。

  1. <?php  
  2. require 'libs/Smarty.class.php'; //包含Smarty 类库文件  
  3. $smarty = new Smarty; //创建一个新的Smarty 对象  
  4. $smarty->display('test7.htm'); //显示页面  
  5. ?> 


模版文件的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代码如下:


 

  1. <?php  
  2. require 'libs/Smarty.class.php'; //包含Smarty 类库文件  
  3. $smarty = new Smarty; //创建一个新的Smarty 对象  
  4. $inc_name = "inc.htm";  
  5. $smarty->assign("inc_name",$inc_name); //对模版中的变量赋值  
  6. $smarty->display('test8.htm'); //显示页面  
  7. ?> 


模板文件如下:


<html>
<head>
<title>Smarty Test</title>
</head>
<body>
{include file=$inc_name}
</body>
</html>
 

 


运行结果与前面相同。


三、如果被包含的文件是模版,则需要使用调用该模版文件的模版来指定其中的变量。将前面的inc.htm改写如下:


{$sentence}

 

  1. <?php  
  2. require 'libs/Smarty.class.php'; //包含Smarty 类库文件  
  3. $smarty = new Smarty; //创建一个新的Smarty 对象  
  4. $inc_name = "inc.htm";  
  5. $sentence = "This is a test!";  
  6. $smarty->assign("inc_name",$inc_name); //对模版中的变量赋值  
  7. $smarty->assign("sentence",$sentence); //对模版中的变量赋值  
  8. $smarty->display('test.htm'); //显示页面  
  9. ?> 


模版文件如下所示:


<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/

没有评论: