smarty变量5

本文深入探讨了使用Smarty模板引擎时如何调用从PHP分配的变量及从配置文件读取的变量,包括直接使用$符号调用PHP变量、使用$smarty->assign()函数分配变量,并详细解释了配置文件中变量的调用方式,如使用#符号或$smarty.config进行访问。同时,文章还提供了实例演示不同场景下的变量使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.从PHP分配的变量

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

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

Eg:

 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}.

OUTPUT:

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`"}不要忘了加``)

Eg:

 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>
 
 
OUTPUT: 
<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>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值