smarty模板引擎从配置文件中获取数据的方法

浏览:828 发布日期:2016/12/22 分类:技术分享
当某个变量值,不希望在程序中写死时,就可以把该变量写到配置文件里,并从中获取(常见的配置样式)。

第一步:先写一个配置文件,如数据库的 db.conf,后缀名conf可以随便写,db.ini也行。文件中内容的格式需要固定:key="值",每一行后面不需要添加分号或者什么,直接回国换行,如:

配置文件:db.conf


复制代码 代码如下:

host = "localhost"
 username = "root"
 password = "123456"
 db_name = "liuyan"


模板文件:temp.tpl

使用{config_load file="db.conf"} 将文件引入进来。注意,如果写相对路径的话,要以访问的页面来看。比如这里,temp.tpl放在templates目录下,db.conf是放在与templates目录同一层,但由于浏览器访问的文件index.php与db.conf同一层,所以,引用时,直接写 {config_load file="db.conf"}  。


复制代码 代码如下:

{config_load file="db.conf"}
 <html>
 <h2>smarty变量操作,从配置文件中获取</h2>
 <p style="color:green;">{#host#}</p>
 <p style="color:red;">{#username#}</p>
 </html>


浏览器访问:index.php

与从php获取变量数据不同,这里不需要用assign分配,而在模板文件里直接加载


复制代码 代码如下:

<?php
 //创建smarty对象
require_once("./libs/Smarty.class.php");
 $smarty = new Smarty();
 $smarty->display("index.tpl");
 ?>
最佳答案
评论( 相关
后面还有条评论,点击查看>>