基本配置,以及数组和变量的使用和文件调用的基本应用
<?php
require(“Smarty/Smarty.class.php”);//smarty类文件
$smarty=new Smarty();//建立smarty实例对象
$smarty->caching=false;//是否启用缓存,一般在调试的期间需要关闭
$smarty->template_dir=”./templates”;//设置模板目录,./表示当前目录
$smarty->compile_dir=”./templates_c”;//设置编译目录
$smarty->cache_dir=”./smarty_cache”;//缓存文件,如果打开缓存必须设置
$smarty->left_delimiter=”{“;//左边界符
$smarty->right_delimiter=”}”;//右边界符
?>index.php页面代码如下
<?php
include(“config.php”);
$name=”这里是第一个Smarty例子”;
$arr[]=array(“name”=>”第1个新闻标题”,”time”=>”2012-04-26″);
$arr[]=array(“name”=>”第2个新闻标题”,”time”=>”2012-04-26″);
$arr[]=array(“name”=>”第3个新闻标题”,”time”=>”2012-04-26″);
$arr[]=array(“name”=>”第4个新闻标题”,”time”=>”2012-04-26″);
$info=array(“标题”,”作者”);
$smarty->assign(“info”,$info);
$smarty->assign(“name”,$name);
$smarty->assign(“arr”,$arr);
$smarty->assign(“test”,”真”);
$smarty->display(“index.htm”);
?>而模板页面index.htm代码如下
{$name}<br />
<!–循环二位数组输出–> {section name=list loop=$arr} {$arr[list].name}-{$arr[list].time}<br /> {/section}
<hr /> {$info[0]}
<hr /> <!–from是循环的数组名,item设置循环变量,下面为无键值–> {foreach from=$info item=id} {$id} {/foreach} <br /> <!–有键值,key是键,item是值,这就是说把数组里面的键值作为j变量,而值作为i变量(可以这样自己理解)–> {foreach from=$info key=j item=i} {$j}-{$i} {/foreach} <br /> <!–文件引入–> {include file=”head.htm”} <br /> <!–文本处理–> {literal} <script language=”javascript”> <!– document.write(“这里都是js代码”); –> </script> {/literal} <br /> {if $test==’真’} 条件为真执行 {else} 条件为假执行 {/if}
1.注释 模板注释被*号包围,例如 {* this is a comment *} smarty注释将不被输出.它是模板内在的注释.
2.易错 模板中使用变量使用{$id}$前面不能有空格
3.保留变量
Smarty 保留变量的名称 | 等同的PHP变量 |
|---|---|
$smarty.get | $_GET |
$smarty.post | $_POST |
$smarty.request | $_REQUEST |
$smarty.session | $_SESSION |
$smarty.cookies | $_COOKIE |
$smarty.env | $_ENV |
$smarty.server | $_SERVER |
$smarty.const | 利用define函数定义的常量 |
4.配置文件变量
$smarty->config_dir = 配置文件的路径;
$smarty->config_load(‘var.conf’);//配置文件名
然后在模板页面可以用{#site_title#}