Sian 发表于 2016-1-27 15:44:28

模板引擎Smarty从配置文件中读取变量

1、设置配置文件路径
<?php
        define(ROOT, dirname(__FILE__));
        include ROOT.'/libs/Smarty.class.php';
        $smarty = new Smarty;
        // 设置模板路径,默认路径为当前php文件所在目录下的templates目录
        $smarty->setTemplateDir(ROOT."/templates");
        // 添加模板路径
//         $smarty->addTemplateDir("./Home");
        // 设置编译文件路径,默认路径为当前php文件所在目录下的templates_c目录
        $smarty->setCompileDir(ROOT."/templates_c");
        // 设置定界符
//         $smarty->setLeftDelimiter("{");
        // 设置配置文件目录
        $smarty->setConfigDir(ROOT."/config");2、创建配置文件,文件名可自定义,如php.conf;
3、设置配置文件内容
border = 1
width = 400
bgcolor = red
color = blue
bg = pink


a = 11111
b = 22222


c = 33333


d = 44444
4、模板调用,使用{config_load file="php.conf" section=index},如果不加sectiion,默认只读取全局变量
Home.index.html----{$content}<br/>
{config_load file="php.conf" section=index}
<body bgcolor="{#bg#}" text="{#color#}">
        <table border="{#border#}" width="{#width#}">
                <tr bgcolor="{#bgcolor#}">
                        <td>{#a#}</td>
                        <td>{#b#}</td>
                        <td>{#c#}</td>
                        <td>{#d#}</td>
                </tr>
                <tr bgcolor="{#bgcolor#}">
                        <td>ddd</td>
                        <td>ddd</td>
                        <td>ddd</td>
                        <td>ddd</td>
                </tr>
                <tr bgcolor="{#bgcolor#}">
                        <td>ddd</td>
                        <td>ddd</td>
                        <td>ddd</td>
                        <td>ddd</td>
                </tr>
        </table>
</body>
5、效果如图所示:

页: [1]
查看完整版本: 模板引擎Smarty从配置文件中读取变量