当前位置:Gxlcms > php框架 > Smarty变量用法详解

Smarty变量用法详解

时间:2021-07-01 10:21:17 帮助过:33人阅读

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

1. 从PHP分配的变量

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

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

示例:

index.php:

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

index.tpl:

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

输出:

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

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

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

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

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

示例:

foo.conf:

  1. pageTitle = "This is mine"
  2. bodyBgColor = "#eeeeee"
  3. tableBorderSize = "3"
  4. tableBgColor = "#bbbbbb"
  5. rowBgColor = "#cccccc"

index.tpl:

  1. {config_load file="foo.conf"}
  2. <html>
  3. <title>{#pageTitle#}</title>
  4. <body bgcolor="{#bodyBgColor#}">
  5. <table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
  6. <tr bgcolor="{#rowBgColor#}">
  7. <td>First</td>
  8. <td>Last</td>
  9. <td>Address</td>
  10. </tr>
  11. </table>
  12. </body>
  13. </html>

index.tpl:

  1. {config_load file="foo.conf"}
  2. <html>
  3. <title>{$smarty.config.pageTitle}</title>
  4. <body bgcolor="{$smarty.config.bodyBgColor}">
  5. <table border="{$smarty.config.tableBorderSize}"bgcolor="{$smarty.config.tableBgColor}">
  6. <tr bgcolor="{$smarty.config.rowBgColor}">
  7. <td>First</td>
  8. <td>Last</td>
  9. <td>Address</td>
  10. </tr>
  11. </table>
  12. </body>
  13. </html>

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

  1. <html>
  2. <title>This is mine</title>
  3. <body bgcolor="#eeeeee">
  4. <table border="3" bgcolor="#bbbbbb">
  5. <tr bgcolor="#cccccc">
  6. <td>First</td>
  7. <td>Last</td>
  8. <td>Address</td>
  9. </tr>
  10. </table>
  11. </body>
  12. </html>

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

更多关于Smarty相关内容感兴趣的读者可查看本站专题:《smarty模板入门基础教程》、《PHP模板技术总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于smarty模板的PHP程序设计有所帮助。

人气教程排行