smarty3.1.30 模板引擎的使用

模板引擎简介

模板引擎就是将用户界面(html)和程序代码(php)分离的一种解决方案。



eg:
没有使用第三方库,使用PHP内置函数,只是简单的字符串处理。
tmp.html文件

<html>
    <head>
        <title>PHP函数分离代码和界面文件</title>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    </head>

    <body>
        <div style="color:red;font-size:20px;">{welcome}</div>
        <br><hr><br>
        <p>{hang}</p>
    </body>
</html>

index.php文件

<?php
    $str = file_get_contents("./tmp.html");
    $str = str_replace('{welcome}',"欢迎",$str);
    $str = str_replace('{hang}',"你",$str);
    echo $str;



smarty特点

  1. 速度快:相对于其他模板引擎,smarty可以提供更快的相应速度
  2. 编译型:模板和PHP文件混排编译
  3. 缓存技术:编译生成的文件在一定缓存时间内生成html静态文件,当我们访问模板时将直接转向静态html文件
  4. 插件技术:可以自定义函数,外来插件
  5. 强大的表现能力



smarty下载与文件介绍

下载smarty

文件解压后:
demo:系统提供的实例文件
libs:核心文件
  – plugins:自定义插件文件夹
  – sysplugins:系统插件文件夹
  – debug.tpl:调试模板
  – Smarty.class.php:Smarty3.0中的核心类文件
  – SmartyBC.class.php:向后兼容类,Smarty2.0版本



smarty使用

  1. 创建文件目录,目录树在后图有
    templates:定义默认模板文件夹
    templates_c:定义编译目录
    cache:定义缓存文件夹
    configs:定义默认配置文件夹

  2. 缓存
    $smarty->caching = true; // 开启缓存
    $smarty->cache_lifetime = 120; // 缓存文件时间

  3. 调试
    $smarty->debugging = true; // 开启调试


初步使用举例 eg,只添加了两个文件:
index.php

<?php

    require './smarty/Smarty.class.php';

    // smarty 相关配置
    $smarty = new Smarty();
    // $smarty->debugging = true;
    $smarty->caching = true;
    $smarty->cache_lifetime = 10;

    if($smarty->isCached("index.tpl"))
    {
        $smarty->display("index.tpl");
        // display 可以在脚本中多次使用,一次展示多个模板
        return;
    }

    // 
    传值到模板
    $smarty->assign("title","welcome");
    $smarty->assign("hang","你");

    // 显示模板
    $smarty->display("index.tpl");

index.tpl

<html>
    <head>
        <title>Smarty 初步</title>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    </head>

    <body>
        <div style="color:red;font-size:20px;">{$title}</div>
        <br><hr><br>
        <p>{$hang}</p>
    </body>
</html>

文件结构

文件结构

恭喜,已入门,是时候表演真正的技术了






smarty 重要的就是Smarty.class.php文件,建议阅读一遍,查看相关属性方法

smarty 相关属性和方法

  1. 左右定界符 left_delimiter 和 right_delimiter
  2. 相关方法
    2.1 $smarty->assign("title","welcome"); // 传welcome 到模板中 替换title
    2.2 $smarty->display("index.tpl"); // 显示并输出相应的模板,目录是默认模板配置目录
    2.3
  3. 修改默认4个文件夹目录
    3.1 $smarty->setTemplateDir("./templates"); // 修改默认模板文件夹
    3.1 $smarty->setCompileDir("./templates_c"); // 修改默认编译文件夹
    3.1 $smarty->setConfigDir("./configs"); // 修改默认配置文件夹
    3.1 $smarty->setCacheDir("./cache"); // 修改默认缓存文件夹
  4. 调试
    $smarty->debugging = true; // 开启调试



编程中的现实问题

  注释代码

{* 这里是smarty注释 *}
<br>
<!-- 这里是HTML注释 -->
<p>{$hang}</p>

  复杂变量(数组、多维数组、对象)的使用

// smarty文件
$smarty->assign("array_yi", array("jh","hn","dy"));
$smarty->assign("array_er", array(array(0,1),array("00","11"),array("000","111")));
$smarty->assign("contacts", array(array("phone"=>"phph"),array("phone" => "555")));
class Person
{
    private $name;
    function __construct($name)
    {
        $this->name = $name;
    }
    public function speak()
    {
        echo $this->name.'在说话...';
    }
}
$smarty->assign('user',new Person("jh"));

// 模板文件
<p>{$array_yi[2]}</p>
<p>{$array_er[2][1]}</p>
<p>{$contacts[1]["phone"]}</p>
<p>{$user->speak()}</p>

// 结果
dy
111
555
jh在说话...

  模板文件中自建临时变量

{assign var='temp' value='声明一个temp变量并赋值'}
{$temp}
{$temp = "另一种方法"}
{$temp}
{$temp = array("jh","声明数组")}
{$temp[1]}

// 结果
声明一个temp变量并赋值 另一种方法 声明数组

  从配置文件中读取变量 - 配置文件在config目录下

// 配置文件
name = Welcome to Smarty!   // 全局变量

[jubu]
jubu_name = jubu_var        // 局部变量


// 模板文件使用配置文件变量
{config_load file = "config.txt"}   // 全局变量使用
{$smarty.config.name}

{config_load file = "config.txt" section="jubu"}    // 局部变量使用
{$smarty.config.name}
{$smarty.config.jubu_name}

  模板使用PHP文件的函数 - 自定义函数

// index.php
function hehe()
{
    return "hehehehe";
}

// 模板文件
{hehe()}

  smarty预保留变量 - 超全局变量

{$smarty.template}             {* 模板的名称 *}
{$smarty.get.page}				{* 相当于 $_GET['page'] *}
{$smarty.post.page}				{* 相当于 $_POST['page'] *}
{$smarty.config}               {* 读取配置文件里变量,后面加变量名。等效{#变量名#} *}
{$smarty.cookies.username}		{* 相当于 $_COOKIES['username'] *}
{$smarty.server.SERVER_NAME}	{* 相当于 $_SERVER['SERVER_NAME'] *}
{$smarty.env.Path}				{* 相当于 $_ENV['Path'] *}
{$smarty.session.id}			{* 相当于 $_SESSION['id'] *}
{$smarty.request.username}		{* 相当于 $_REQUEST['username'] *}
{$smarty.now}                  {* 获取当前时间戳 *}
{$smarty.current_dir}          {* 获取当前模板目录 *}
{$smarty.version}              {* 获取当前Smarty版本 *}
{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}

  变量调节器(文本格式化)

{$var|capitalize}              {* 首字母大写 *}
{$var|count_characters:true}   {* 字符计数 *}
{$var|cat:var2}                {* 连接字符串 *}
{$var|count_paragraphs}        {* 段落计数 *}
{$var|count_sentences}         {* 句子计数 *}
{$var|count_words}             {* 计算词数 *}
{$var|data_format:"%Y%m%d"}    {* 时间格式化 *}
{$var|default:"value"}         {* 如果变量为空或为定义,那么采用默认值 *}
{$var|escape}                  {* 编译转码 *}
{$var|indent:10:"*"}           {* 首行缩进,后面的参数表示每个缩进字符要放的字符 *}
{$var|lower}                   {* 字符串小写 *}
{$var|nl2br}                   {* \n转<br/> *}
{$var|regex_replace:"/[\t\n]/",""} {* 正则替换 *}
{$var|spacify:"^^"}            {* 在字符之间插入相应字符如^^ *}
{$var|string_format:'%d'}      {* 字符串格式化 *}
{$var|strip:'*'}               {* 去掉重复空格 *}
{$var|strip_tags}              {* 去除html标签 *}
{$var|truncate:30:'...'}       {* 字符串截取,注意,优缺点 *}
{$var|upper}                   {* 大写 *}
{$var|wordwrap:30:'<br>'}      {* 行宽约 *}

// 可以自建调节器
// 组合调节器
{$var|lower|truncate:30|spacify}



smarty 模板内置函数

  {debug} 开启调试窗口

  捕获一段HTML代码

{capture name="content"}
<h1>h1</h1><br>
<center>center</center>
{/capture}

{$smarty.capture.content}

  foreach - PHP方式

{foreach $array_yi as $key => $val}
    {$key} {$val}
{/foreach}

  foreach - smarty语法进行遍历

{foreach from=$array_yi key="key" name="array_yi" item="val"}
    {$key} {$val}
{/foreach}

  二维数组循环遍历 - 方式一

{foreach $array_er as $val}
    {$val[1]}
{/foreach}

  二维数组循环遍历 - 方式二

{foreach from=$array_er key="key" name="array_er" item="val"}
    {$val@iteration}{$val[0]}
{/foreach}
共循环了{$smarty.foreach.array_er.total}次 | {$val@total}次


// 内置其他函数
{$smarty.foreach.name.index}       {* @index 下标0 *} 
{$smarty.foreach.name.iteration}   {* @iteration 迭代(当前是第几次循环),默认从1开始 *}
{$smarty.foreach.name.first}       {* @first bool当时第一次该值为真 *}
{$smarty.foreach.name.last}        {* @last bool当时最后一次该值为真 *}
{$smarty.foreach.name.show}        {* @show 数据显示true显示数据,false不显示数据 *}
{$smarty.foreach.name.total}       {* @total 循环的总次数 *}

  二维数组循环遍历 - 方式三

// name:代表section名称,在循环过程中,会作为索引,必选
// loop:代表循环数组,由其来确定循环的次数,必选
// start:默认从第几个元素开始遍历
// step:每次循环次数,默认是1
// max:最大循环次数

{section name=索引 loop=循环数组 start=开始(0) step=步阶(1) max=最大循环次数}
{/section}

// 举例
{section name="index" loop=$array_er}
    {$array_er[index][0]}
    {$array_er[index][1]}
{/section}

  fetch 载入文件/引入文件到当前文件,并赋值给变量

{fetch file="./configs/other.config" assign="ddd"}
{$ddd}
// 结果 => 输出改文件所有信息

  include 模板

{include file='other.html'}

  include_php 文件

{include_php file='other.php'}

  if elseif else

{if empty($title)}
have title
{elseif $title}
title is {$title}
{else}
no title
{/if}

  literal 字符原样输出,不解析

{literal}
    {$title}
{/literal}

// 结果
{$title}

  strip 字符原样输出,不解析

{strip}
    ....
{/strip}

 // 功能及应用:去除任何位于{strip}{/strip}标记数据中记录的首尾空格和回车,
 // 可以保证模板容易理解且不用担心多余的空格导致问题

  counter - 进行计数

  cycle 实现轮显效果

  {html_image file=”pumplink.png”} 引用一张图片

  {html_table loop=$data cols=4 table_attr=”border=0”} 循环输出数组到一张表

  html_checkboxes 、 html_options 、 html_radios 作为拓展需要使用去查询





编写PHP程序(非模板程序)上面要注意的哪些 和 辅助开发函数、变量

  SMARTY_DIR 常量 = Smarty.class.php文件的路径
  assign 分配变量到模板文件
  assignByRef 分配变量到模板文件(引用)

$hang = "你";
$smarty->assign("hang",$hang);
$hang = "我们";
// 结果$hang = "你";
$smarty->assignByRef("hang",$hang);
$hang = "我们";
// 结果
我们

  append 追加数据到数组,过程分为两步
    第一是追加数据到数组中
    第二分配变量到模板文件中(也就不需要assign赋值了)
  appendByRef 追加元素地址到数组中
  clearAllAssign 清除所有赋值变量
  clearAssign 清除指定变量的值
  clearCache 清理缓存
  configLoad 载入配置文件
  clearConfig 清除配置文件信息
  display 执行输出并显示指定页面
  fetch 载入文件到字符串 - 不同于模板中的fetch函数

// 把结果生成临时html文件存储起来 = 模拟静态页 = 存储静态页
require './smarty/Smarty.class.php';
$smarty = new Smarty();
$smarty->assign("title","welcome");

$str = $smarty->fetch("index.tpl");
file_put_contents('./'.time().'.html', $str);
// 判断模板文件是否存在
if($smarty->templateExists("index.tpl"))
{
    $smarty->display("index.tpl");
}
else
{
    trigger_error('没有找到模板文件', E_USER_ERROR);
}
// 判断有没有缓存某个文件,如果缓存了就直接输出
if($smarty->isCached("index.tpl"))
{
    $smarty->display("index.tpl");

    // display 可以在脚本中多次使用,一次展示多个模板
}
$smarty->clearCache('index.tpl')  // 清除指定模板缓存文件
$smarty->clearAll() // 清除所有缓存文件





过滤器

如果页面有临时缓存,谨慎使用过滤器

分为三种:Prefilters:预过滤器 、Postfilters:后过滤器 、Outputfilters:输出过滤器

过滤图

eg:

$smarty->assign("guolv","fff333 fff222 fff111");
function f3($data)
{
    file_put_contents('./'.time().'.html', $data);
    return str_replace("fff333" , "333fff" , $data);
}
// 输出过滤器
$smarty->registerFilter('output', 'f3' );





缓存

  设置

$smarty->setCacheDir($cache_dir)  // 设置缓存目录,不设置默认cache文件中
$smarty->caching=true  // 开启缓存机制caching=true,默认为false
$smarty->cache_lifetime = 120; // 缓存时间,单位为秒

  优势

1、速度要更快
2、减少服务器I/O开销,减小服务器的压力
3、减小对服务器数据库的压力

  缓存在什么时候会重新生成
  
1、时间过期
2、缓存被删除
3、编译文件改变
4、模板文件改变

  检测模板有没有被缓存

if($smarty->isCached("index.tpl"))
{
    $smarty->display("index.tpl");
}

  删除缓存的方式

$smarty->clearCache('tpl.tpl')     // 清除指定模板缓存文件
$smarty->clearAll() // 清除所有缓存文件

// 数据库的增删改之后,就要清除该缓存
// update后要清除的缓存
$smarty->clearCache("index.html"); //清除浏览缓存
$smarty->clearCache("edit.html",$_POST['id']); //清除修改表单缓存

// 多级缓存
if(!$smarty->isCached("stu/edit.html",$_GET['id'])){
    $stu = $mod->find($_GET['id']);
    $smarty->assign("data",$stu);
}
$smarty->display("stu/edit.html",$_GET['id']);

  模板中局部缓存 (添加true参数)

// 方法一 , 刷新页面会提示,
$smarty->assign("linshi","linshi_huancun",true);
{if empty($linshi)}
no
{else}
yes-{$linshi}
{/if}


// 方法二 , 刷新页面会提示,
$smarty->assign("linshi","linshi_huancun",true);
{nocache}
    {if empty($linshi)}
    no
    {else}
    yes-{$linshi}
    {/if}
    这一块会缓存,不会缓存上面的变量
{/nocache}

  单页面多缓存

当访问某个页面 news.php?id=5 时,第一次会查询数据库并缓存,之后就直接显示缓存文件的内容,减小服务器、数据库压力

// 只需要在display后面跟上id属性
$smarty->display("index.tpl",$_GET['id']); 

// 结果
会在cache文件夹下,会根据id值多生成不同的缓存文件

  缓存集合

$smarty->display("index.tpl",$_GET['id'] . '|' .  $_GET['page']); 

// 结果
同单页面多缓存,会在cache文件夹下,根据多个条件生多生成多个的缓存文件
比如:
45^2^1a4de3f1e073e6a12c90ba07969d236f14.index.tpl.php   
45^3^1a4de3f1e073e6a12c90ba07969d236f14.index.tpl.php
8^6^1a4de3f1e073e6a12c90ba07969d236f14.index.tpl.php



结束

文章内容是边学习边写示例代码后做的笔记,初次上传,有什么纰漏还望大家指正。

1、参考博客链接 - 参考链接
2、参考博客链接 - 参考链接


最后引用别人的一张图片,感觉还不错
smarty借鉴图

猜你喜欢

转载自blog.csdn.net/yihaiweiyi/article/details/78327152