PHP模板引擎Smarty

目的是要使用PHP程序美工分离

1、Smarty的配置 :smarty_inc.php

<?php
include_once("Smarty/Smarty.class.php");//包含smarty类文件

$smarty = new Smarty();
$smarty->config_dir = "smarty/SmartyBC.class.php";
$smarty->template_dir = "./templates"; //设置模板目录
$smarty->compile_dir = "./templates_c"; //设置编译目录

$smarty->caching = true; //是否使用缓存,项目在调试期间,不建议启用缓存
$smarty->cache_dir = "./smarty_cache"; //缓存文件夹
$smarty->cache_lifetime=60;//缓存停留时间

//----------------------------------------------------

//左右边界符,默认为{},但实际应用当中容易与JavaScript相冲突

//----------------------------------------------------
$smarty->left_delimiter = "{";
$smarty->right_delimiter = "}";

?>

2、在显示的页面中

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


模板中循环数组的方法:

{section name=s loop=$stu}

{$stu[s].name}

{sectionelse} 

无内容

{/section}
3、smarty变量操作符

语法中使用"|"应用变量操作符,多个参数用":" 分隔开来

eg:{$name|truncate:10:"..."}

常用变量符:

capitalize[首字母大写]

count_characters[计算字符数]

cat [连接字符串]

count_paragraphs [计算段落数]

count_sentences [计算句数]

count_words[计算词数]

date_format [时间格式]

default[默认]

escape [转码]

indent[缩进]

lower [小写 ]

nl2br[换行符替换成<br />]

regex_replace[正则替换]

replace[替换]

spacify[插空]

string_format[字符串格式化]

strip[去除(多余空格)]

strip_tags[去除html标签]

truncate[截取]

upper[大写]

wordwrap[行宽约束]

4、smarty内置函数

(1)foreach处理一维数组

=======无键值数组
{foreach from=$name item=id}
id: {$id}<br>
{/foreach}

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

(2)include

{include file="header.htm"}
{include file="D:\www\head.htm"}
{include file='head.htm' title="Main Menu"}

(3)if语句

{if $name=='ok'}

{else}

{/if}

(4)literalstrip 文本的处理技巧

literal 数据将被当作文本处理,此时模板将忽略其内部的所有字符信息. 该特性用于显示有可能包含大括号等字符信息的 javascript 脚本

strip标记中数据的首尾空格和回车.这样可以保证模板容易理解且不用担心多余的空格导致问题


5、smarty缓存使用

(1)缓存配置:


  
  
$smarty->cache_dir = "/caches/"; //缓存目录
$smarty->caching = true; //开启缓存,为flase的时侯缓存无效
$smarty->cache_lifetime = 60; //缓存时间
(2)缓存的使用与清除

$smarty->display('cache.tpl', cache_id);  //创建带ID的缓存
$smarty->clear_all_cache(); //清除所有缓存
$smarty->clear_cache('index.htm'); //清除index.tpl的缓存
$smarty->clear_cache('index.htm',cache_id); //清除指定id的缓存
smarty3.0以上换为:$smarty->clearAllCache();
smarty3.0以上换为:$smarty->clearAllCache();


(3)局部缓存
insert函数默认是不缓存的。并且这个属性不能修改
index.htm模板

<div>{insert name="get_time"}</div>
index.php 网页
function insert_get_time(){
      return date("Y-m-d H:m:s");
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值