发布于 2016-05-14 03:36:40 | 133 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Smarty模板引擎

Smarty是一个使用PHP写出来的模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。简单的讲,目的就是要使PHP程序员同前端人员分离,使程序员改变程序的逻辑内容不会影响到前端人员的页面设计,前端人员重新修改页面不会影响到程序的程序逻辑,这在多人合作的项目中显的尤为重要。


这篇文章主要介绍了Smarty变量用法,结合实例形式分析了php分配变量与配置文件读取变量的具体使用方法,需要的朋友可以参考下

本文实例讲述了Smarty变量用法。分享给大家供大家参考,具体如下:

1. 从PHP分配的变量

调用从PHP分配的变量需在前加"$"符号.(译注:同php一样)

调用模板内的assign函数分配的变量也是这样.(译注:也是用$加变量名来调用)

示例:

index.php:


$smarty = new Smarty;
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastLoginDate', 'January11th, 2001');
$smarty->display('index.tpl');

index.tpl:


Hello {$firstname}, glad to see you couldmake it.
<p>
Your last login was on {$lastLoginDate}.

输出:


Hello Doug, glad to see you could make it.
<p>
Your last login was on January 11th, 2001.

2. 从配置文件读取的变量

配置文件中的变量需要通过用两个"#"或者是smarty的保留变量 $smarty.config.来调用(后面会讲到)

第二种语法在变量作为属性值并被引号括住的时候非常有用.

(译注:举个例子 {include file="#includefile#"} 这样#includefile#将被当作字符处理,而不表示配置文件变量,但可以这样表示{include file="`$smarty.config.includefile`"}不要忘了加``)

示例:

foo.conf:


pageTitle = "This is mine"
bodyBgColor = "#eeeeee"
tableBorderSize = "3"
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"

index.tpl:


{config_load file="foo.conf"}
<html>
<title>{#pageTitle#}</title>
<body bgcolor="{#bodyBgColor#}">
<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
<tr bgcolor="{#rowBgColor#}">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>

index.tpl:


{config_load file="foo.conf"}
<html>
<title>{$smarty.config.pageTitle}</title>
<body bgcolor="{$smarty.config.bodyBgColor}">
<table border="{$smarty.config.tableBorderSize}"bgcolor="{$smarty.config.tableBgColor}">
<tr bgcolor="{$smarty.config.rowBgColor}">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>

上述两种模板写法都输出:


<html>
<title>This is mine</title>
<body bgcolor="#eeeeee">
<table border="3" bgcolor="#bbbbbb">
<tr bgcolor="#cccccc">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>

配置文件的变量只有在它们被加载以后才能使用.



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务