PHP头条
热点:

30分钟速通,PHP模板发动机Smarty


30分钟速通,PHP模板引擎Smarty

30分钟速通,PHP模板引擎Smarty

分类:?技术文档?PHP+MySql?标签:

以下内容是是PHP100的PHP教程视频第27,28,29,30讲的浓缩,并添加一些smarty中文手册的补充材料,简练明了,如果看不懂的话。。。还是先看下27-30讲的视频较好。

?

smarty配置:

?

include("smarty/smarty.class.php"); //调用smarty配置文件,默认在smarty根目录下。
$smarty = new smarty(); //新建一个对象
$smarty->caching = false; //关闭缓存,有利于测试。如需开启缓存,改为true
$smarty->cache_lifetime = 60 //设置缓存存活时间,单位秒,必须把caching=true下才作用
$smarty->config_dir = "./configs"; //设置配置文件目录,可用$smarty->config_load()方法来调用配置文件
$smarty->template_dir = "./templates"; //设置模板目录
$smarty->compile_dir = "./templates_c"; //设置编译目录
$smarty->cache_dir = "./caches"; //设置缓存目录
$smarty->left_delimiter = "{"; //缓存左边界符
$smarty->right_delimiter = "}"; //缓存右边界符

?

?

smarty应用:

?

$smarty->assign("模板变量","值/数组");
$smarty->display("模板名称");

例:

index.php的代码:?
$value = "bluesdog say : learn smarty only 30 minutes"?
$smarty->assign("content",$value); //进行模板变量替换?
$smarty->display("index.htm") //该文件就是模板文件,应该在./templates模板目录下?

index.htm的代码:?

{if $content ne ""}?
{$content}?
{/if}?
?

  • 以上类似:$smarty->cache_lifetime = n 都是smarty的变量
  • 以上类似:$smarty->display(template name) 都是smarty的方法
  • 以上类似:{if $content ne ""}…{/if} 都是smarty的函数

?

?

smarty循环:

smarty共有2种循环函数,section循环多维数组,foreach循环一维简单数组。

?

section举例(参数name和loop必不可少,name=自定义循环名 loop=用来循环的变量):
{section name=s loop=$stu}
{$stu[s].name}
{sectionelse}
无内容
{/section}

例:新闻列表循环

index.php代码:
include("smarty_inc.php"); //smarty配置文件
$news[]=array("title"=>"新闻标题第一条","date"=>"2009-01-01");
$news[]=array("title"=>"新闻标题第二条","date"=>"2009-01-02");
$news[]=array("title"=>"新闻标题第三条","date"=>"2009-01-03");
$news[]=array("title"=>"新闻标题第四条","date"=>"2009-01-04");
$news[]=array("title"=>"新闻标题第五条","date"=>"2009-01-05");
$row=array("标题","作者","当前页");
$smarty->assign("row",$row);
$smarty->assign("news",$news);
$smarty->display("index.htm");

index.htm代码:

{$row[0]} | {$row[1]} | {$row[2]}




    {section name=list loop=$news}

  • {$news[list].title}-{$news[list].date}

  • {/section}

foreach举例(参数from和item必不可少,item=自定义循环名 from=用来循环的变量):
//无键值数组
{foreach from=$name item=id}
id:{$id}

//有键值数组
{foreach key=j item=v from=$name}
{$j}:{$v}

{/foreachelse}
没有内容了
{/foreach}

例:

include(“smarty_inc.php”); //smarty配置文件?
$value=array(1,3,5,7);
$value2=array(‘a’=>’php’,’b’=>’java’,’c’=>’C++);
$smarty->assign(‘name’,$value);
$smarty->assign(‘name2’$value2);
$smarty->display(“index.html”);

index.html代码:
{foreach from=$name item=id}
数组:{$id}

{/foreach}
{foreach from=$name item=id key=k}
数组键值:{$k} 数组内容:{$id}

{/foreach}


?

?

smarty内置函数:

?

(注:这些内置函数都是写在模板文件上的,如index.html,index.tpl。foreach和section也是smarty的内置函数,由于较为重要,所以在上一段单独列出)

?

include多功能使用

{include file="header.html"}
{include file="D:\www\head.htm"} // 可以使用绝对路径
{include file="head.html" title="bluesdog"} // 如果head.html中有{$title},则直接替换成bluesdog

?

IF条件语句的使用

{if $name==’ok’}

{else}

{/if}

?

literal用以忽略页面中的javascript的{}

{literal}

相关文章

PHP之友评论

今天推荐