smarty是一个PHP模板引擎,用于区分美工与程序
可以在www.smarty.net官方网站下载,有smarty 2.X、smarty 3.X,smarty 3生成的编译后的文件很大,暂时使用Smarty 2
Smarty/libs包含了核心文件
test.php
<?php
require('./libs/Smarty.class.php');//包含smarty类文件
$smarty = new Smarty;//创建smarty对象
$smarty->template_dir = './templates/';//指定模板文件所在位置
$smarty->compile_dir = './templates_c/';//指定编译后的文件所在位置
$smarty->config_dir = './configs/';//指定配置文件
$smarty->cache_dir = './cache/';//缓存文件
$smarty->assign('name','ChuangRain');//分配变量
$smarty->display('index.html');//显示templates/index.html
index.html{* Smarty *}//注释
hello,{$name}!//输出 hello,ChuangRain
如果是现在这种{}标签,js会出问题,因为在js中会用到{},在smarty编译时会将其当作是smarty要编译的东西,会出错。
例index.html
{* Smarty *}
hello,{$name}!
<script>
function test(){
alert('11111111111111');
}
test();
</script>
运行时会出现下面的错误信息
Fatal error: Smarty error: [in index.html line 7]: syntax error: unrecognized tag: alert('11111111111111'); (Smarty_Compiler.class.php, line 446) in D:\AppServ\www\Smarty\libs\Smarty.class.php on line 1093
可以用literal来忽略{},
{literal}
<script>
function test(){
...
}
</script>
{/literal}
<!-- 在{/literal}和{/literal}之间的内容会被当作文本来处理,忽略其内容 -->
但是一般都是修改smarty的标签,来解决这个问题
$smarty->left_delimiter = "<{";//左标签 <{
$smarty->right_delimiter = "}>";//右标签 }>
在模板中使用变量就可以直接用 <{$name}>