smarty 从配置文件读取变量

smarty变量分3种:

Variables [变量]

Variables assigned from PHP [从PHP分配的变量]
Variables loaded from config files [从配置文件读取的变量]
{$smarty} reserved variable [{$smarty}保留变量]

从配置文件获取的变量

配置文件获取的变量,可以通过 井号引用起来访问如#hash_marks#, 或者通过Smarty变量$smarty.config来访问。 后者在使用其他属性或者是访问别的变量值时比较有用,如$smarty.config.$foo。

Example 4.7. 配置变量

配置文件foo.conf例子:

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

示范使用#hash#方式的模板:

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

    

示范使用 $smarty.config方式的模板:

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

配置变量必须先载入配置文件才能使用。 这个过程会本文档的 {config_load}说明里面解释。

参见 变量 和 $smarty保留变量

参考:http://www.smarty.net/docs/zh_CN/language.config.variables.tpl

再说一下配置文件:

Chapter 9. 配置文件

置文件可以让设计者将全局的模板变量以文件形式管理起来。 其中一个例子是管理模板的颜色值: 通常如果你需要从程序中更改颜色主题,那么你需要找到每个模板文件, 并且修改它们的颜色值。 通过配置文件,颜色值被统一放置到配置文件内,你只需要修改这个文件即可。

Example 9.1. 配置文件语法示例

# global variables
pageTitle = "Main Menu"
bodyBgColor = #000000
tableBgColor = #000000
rowBgColor = #00ff00

[Customer]
pageTitle = "Customer Info"

[Login]
pageTitle = "Login"
focus = "username"
Intro = """This is a value that spans more
           than one line. you must enclose
           it in triple quotes."""

# hidden section
[.Database]
host=my.example.com
db=ADDRESSBOOK
user=php-user
pass=foobar

配置文件中的配置变量可以被引用起来,但不是必须的。 你可以使用单引号或者双引号。 如果有的值会跨度不止一行的,那么你需要用三引号(""")把它们括起来。 你可以将任何形式的注释放到配置文件中,但这不是有效的配置文件语法。 我们建议使用# (井号) 来作为注释行的开头。

上面配置文件的例子有两段。 段落的名字用[方括号]括起来。 段落名称可以是任意字符,但不包括[ 或 ]符号。 最顶部的四个值是全局变量,也就是不在段落内的变量。 这些全局变量将总是被载入。 当一个特定的段落被载入,那么段落的变量以及全局变量都会被载入。 如全局变量和段落变量都有同样的变量,那么将使用段落的变量。 如有相同的两个变量在同一个段落,最后一个将会被使用,除非 $config_overwrite设置被关闭。

配置文件可以使用内置的函数 {config_load}来载入,或者通过configLoad()函数进行载入。

你可以通过在变量名或段落名前面加上点号(.),来隐藏变量或者整个段落,如[.hidden]。 这个技巧在你的程序使用配置文件保存一些敏感信息,但这些信息又不希望模板引擎使用时,非常有用。 如果是第三方来对模板进行修改,你也可以保证他们不会在载入配置文件时,读取到这些敏感信息

配置文件(或资源)将使用相同的模板资源来进行载入。 这意味着配置文件还可以从数据库中载入,如$smarty->configLoad("db:my.conf")

参见 {config_load}$config_overwrite$default_config_handler_func,getConfigVars()clearConfig() 和 configLoad()

参考:http://www.smarty.net/docs/zh_CN/config.files.tpl

原文地址:https://www.cnblogs.com/youxin/p/3556459.html