zoukankan      html  css  js  c++  java
  • Smarty模板快速入门

    文件下载

    1、下载地址:http://www.smarty.net/

    2、我下载的版本是3.1.27 ,将下载的文件smarty-3.1.27.zip解压出来,然后将libs文件夹的所有文件复制到你的项目中(可重新命名libs文件夹名称)

    3、目录结构,如下图


    4、本文相关实例完整代码下载:下载地址

    Smarty相关配置

    1、配置代码

    //获取硬路径
    define('ROOT_PATH', dirname(__FILE__).'/');
    //引入smarty核心类文件
    require ROOT_PATH.'smarty/Smarty.class.php';
    
    //自定义模板文件目录,此时是将Smarty默认路径重写了一遍
    $_smarty->template_dir = './templates/';
    //编译文件目录
    $_smarty->compile_dir = './templates_c/';
    //配置变量目录
    $_smarty->config_dir = './configs/';
    //缓存目录
    $_smarty->cache_dir = './cache/';
    //是否开启缓存,开发阶段,要关闭缓存,1/true表示开启缓存
    $_smarty->caching = 1;
    //缓存的时间,默认是1小时
    $_smarty->cache_lifetime = 60*60*24;
    //左定界符,{}是Smarty默认的左右定界符
    $_smarty->left_delimiter = '{';
    //右定界符
    $_smarty->right_delimiter = '}';

    2、配置说明

    (1)在项目下面要提前新建几个文件夹:templates(放模板文件,如:index.tpl)、templates_c(放编译文件,如、debef1afdc8f3ca548e8845c5d6c8dc1a075b2d5_0.file.index.tpl.php)、configs(放配置文件,如:config.conf)、cache(放缓存文件,如:debef1afdc8f3ca548e8845c5d6c8dc1a075b2d5.index.tpl.php)。其中templates_c和cache文件夹会自动生成,其相应的编译文件和缓存文件也会自动生成。config目录下的配置文件的后缀可以随便定义,为了容易识别一般定义为.conf

    (2)左右定界符定义成{ }后,.tpl文件里面就不能像html文件里面那样写JS和CSS代码(符号冲突)。解决办法:可以将定界符定义成其他字符或字符串,还可以将{ }用Smarty的内置函数打印出来,不过常用的方法是将JS、CSS代码和HTML代码(.tpl文件中)分离。

    (3).tpl文件类似于HTML文件,不同的是按照smarty语法可以解析里面的一些变量。.conf配置文件的书写格式是:键=值 (每一行表示一个键值对,键、值都不需要引号)

    Smarty解析变量

    实例代码:

    smarty.inc.php(下面的实例也会用到)

    <?php
    
    //获取硬路径
    define('ROOT_PATH', dirname(__FILE__).'/');
    //引入smarty核心类文件
    require ROOT_PATH.'smarty/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/';
    //是否开启缓存,开发阶段,要关闭缓存,1/true表示开启缓存
    $_smarty->caching = 1;
    //缓存的时间,默认是1小时
    $_smarty->cache_lifetime = 60*60*24;
    //左定界符,{}是Smarty默认的左右定界符
    $_smarty->left_delimiter = '{';
    //右定界符
    $_smarty->right_delimiter = '}';
    
    ?>

    config.conf(下面的实例也会用到)

    site=小易blog
    url=http://blog.csdn.net/oldinaction

    index.php

    <?php
    
    //导入smarty配置文件
    require 'smarty.inc.php';
    
    $_title = 'Smarty模板引擎';
    $_array1 = array('1', '2', '3');
    $_array2 = array('1'=>'一', '2'=>'二', '3'=>'三');
    Class Smalle {
    	public $site = 'AEZO';
    	public function url(){
    		return 'http://www.aezo.cn';
    	}
    }
    
    define('SMALLE', '微信号:smallelife');
    
    //分配普通变量,第一个参数是Smarty模板引擎变量,第二个参数是PHP变量
    $_smarty->assign('title', $_title);
    $_smarty->assign('a', 1);
    $_smarty->assign('b', 2);
    //分配数组变量
    $_smarty->assign('array1', $_array1);
    $_smarty->assign('array2', $_array2);
    //分配对象变量
    $_smarty->assign('smalle', new Smalle());
    
    //引入模板
    $_smarty->display('index.tpl');
    
    ?>

    index.tpl

    {config_load file='config.conf'} {*注释:此时文件目录不需config这一层,因smarty.inc.php已经定义了配置文件目录*}
    
    <!doctype html>
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    		<title>{$title}</title>
    	</head>
    <body>
    
    数组变量显示结果:<br />
    {$array1[1]}<br />
    {$array2.1}<br />
    ----------------------<br />
    
    对象变量显示结果:<br />
    {$smalle->site}<br />
    {$smalle->url()}<br />
    ----------------------<br />
    
    模板中可进行计算:<br />
    {$a+$b}<br />
    ----------------------<br />
    
    Smarty保留变量:<br />
    {*注释:保留的$smarty.const变量专门针对常量,这样就不需要将常量像变量一样分配了*}
    {$smarty.const.SMALLE}<br />
    ----------------------<br />
    
    config目录下的配置文件中的键值对:<br />
    {*注释:下面两种表示方法都可以*}
    {$smarty.config.site}<br />
    {#url#}<br />
    ----------------------<br />
    
    </body>
    </html>

    效果展示:

    在浏览器访问 http://127.0.0.1/smarty/index.php 效果如下


    Smarty自定义函数

    此处说的自定义函数主要包括Smarty提供的自定义函数和开发者自己写的函数称为自定义函数。开发者以插件的形式自定义的函数,文件要放在Smarty核心文件的plugins目录下。

    function.smfunc.php 自定义函数文件,放在plugins目录下

    <?php
    /**
     * Smalle 以插件的形式自定义的函数
     * 注意:
     * 1、文件格式为function.xxx.php
     * 2、函数名为smarty_function_xxx($params){}
     * 3、使用:{smfunc a=1 b=2} a、b参数和其值会以关联数组的形式传给此函数的第一个参数
     */
    
    function smarty_function_smfunc($_arr){
    
        $_cout = $_arr['a'] + $_arr['b'];
        return $_cout;
    }
    
    ?>

    func.php

    <?php
    
    //导入smarty配置文件
    require 'smarty.inc.php';
    
    $_smarty->assign('array', array('a'=>'一','b'=>'二','c'=>'三'));
    
    //引入模板
    $_smarty->display('func.tpl');
    
    ?>

    func.tpl

    <!doctype html>
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    		<title>自定义函数</title>
    	</head>
    <body>
    
    Smarty的自定义函数举例:<br />
    {html_checkboxes options=$array selected=b}<br />
    ----------------------<br />
    
    开发者以插件的形式自定义的函数举例:<br />
    {smfunc a=1 b=2}<br />
    ----------------------<br />
    
    </body>
    </html>

    效果展示:

    Smarty内置函数

    builtFunc.php

    <?php
    
    //导入smarty配置文件
    require 'smarty.inc.php';
    
    /**
     * {insert}内置函数中调用的即为此处的函数
     * 注意:
     * 1、函数命名:insert_xxx  (xxx指{insert}内置函数中name的值)
     * 2、{insert}内置函数中的参数会以数组的形式传递给此函数
     */
    function insert_getConfig($_arr){
    	return $_arr['site'].':'.$_arr['url'];
    }
    
    $_smarty->assign('arr',array('a'=>'一','b'=>'二','c'=>'三'));
    
    //引入模板
    $_smarty->display('builtFunc.tpl');
    
    ?>

    builtFunc.tpl

    <!doctype html>
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    		<title>内置函数</title>
    	</head>
    <body>
    内置函数举例1:<br />
    ----------------------示例1<br />
    {assign var="flag" value=false}
    {assign var="i" value=1}
    {if $flag}
    	0
    {elseif $i == 2}
    	2
    {else $i < 2}
    	1
    {/if}
    <br /><br />
    
    ----------------------示例2<br />
    {foreach $arr as $item}
    	{$item@key}=>{$item}
    {/foreach}<br />
    
    一共循环了{$item@total}次<br />
    
    {foreach $arr as $key=>$value}
    	{$key}=>{$value}
    {/foreach}<br /><br />
    
    ----------------------示例3<br />
    {for $var=1 to 10}
    	{$var}
    {/for}<br />
    {for $var=2 to 10 step 2}
    	{$var}
    {/for}<br />
    {for $var=2 to 10 max=3}
    	{$var}
    {/for}<br /><br /><br />
    
    内置函数举例2:<br />
    ----------------------示例4(显示左右定界符)<br />
    {ldelim}  {rdelim}<br /><br />
    
    ----------------------示例5(literal显示代码块)<br />
    {literal}
    	function(){
    		alert(1);
    	}
    {/literal}<br /><br />
    
    ----------------------示例6<br />
    {assign var="name" value="smalle"}
    {$name}<br /><br />
    
    -->{ldelim}config_load file="example.conf"{rdelim}用来从配置文件中加载config变量到模版<br />
    使用 $smarty.config.键 或者 #键# 获取<br /><br />
    
    -->{ldelim}strip{rdelim}{ldelim}/strip{rdelim}压缩源代码,去掉空格和换行
    ----------------------示例7<br />
    {strip}
    <table border=0>
    	<tr>
    		<td>
    			<font color="red">This is a test</font>
    		</td>
    	</tr>
    </table>
    {/strip}<br />
    
    -->{ldelim}insert name="insertName"{rdelim}插入函数。所包含的内容不会被缓存,每次调用模板都会执行<br />
    ----------------------示例8<br />
    {config_load file="config.conf"}
    {insert name="getConfig" site=#site# url=#url#}<br />
    
    </body>
    </html>

    效果展示:

    Smarty变量调节器

    同自定义函数一样,开发者也可以以插件的形式自定义变量调节器,当然Smarty也提供了一些变量调节器。自定义的插件文件也要放在plugins目录下。

    modifier_smtruncate.php(放在plugins目录下)

    <?php
    /**
     * Smalle 自定义变量调节器(截取字符串)
     * 注意:
     * 1、文件命名格式:modifier.xxx.php
     * 2、函数的命名格式:smarty_modifier_xxx($params){}
     * 3、使用:{$str|smtruncate:0:20:'utf-8':'###'} $str是注入进来的变量,会传给函数的第一个参数
     */
    
    function smarty_modifier_smtruncate($_str, $_length, $_start=0, $_encoding='utf-8', $_endStr='...'){
        if(mb_strlen($_str) > $_length){
            return mb_substr($_str, $_start, $_length, $_encoding);
        } else {
            return mb_substr($_str, $_start, $_length, $_encoding).$_endStr;
        }
        
    }
    
    ?>

    mvar.php

    <?php
    
    //导入smarty配置文件
    require 'smarty.inc.php';
    
    $_url = 'http://www.aezo.cn/tag=<strong>小易你好啊</strong>';
    $_smarty->assign('url', $_url);
    
    //引入模板
    $_smarty->display('mvar.tpl');
    
    ?>

    mvar.tpl

    <!doctype html>
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    		<title>变量调节器</title>
    	</head>
    <body>
    
    Smarty的变量调节器举例<br />
    --regex_replace[正则替换]<br />
    {$url|regex_replace:"/http/":"https"}<br /><br />
    
    --strip_tags[去除html标签],参数false指标签不用空格替换<br />
    {$url|strip_tags:false}<br /><br />
    
    --组合变量调节器<br />
    {$url|regex_replace:"/http/":"https"|strip_tags:false}<br />
    ----------------------<br /><br />
    
    开发者以插件的形式自定义的变量调节器举例:<br />
    {$url|smtruncate:33}<br />
    ----------------------<br />
    
    </body>
    </html>

    效果展示:

    Smarty缓存机制

    要先开启缓存($_smarty->caching = 1;),下面的功能才能实现

    cache.php

    <?php
    
    //设置时区
    date_default_timezone_set('Asia/Shanghai');
    
    //导入smarty配置文件
    require 'smarty.inc.php';
    
    //多重缓存,访问 http://127.0.0.1/smarty/cache.php?id=1&page=1 改变参数的值
    $_id = @$_GET['id'];
    
    //部分片段不缓存
    function smarty_block_nocache($param, $content, $smarty) {
        return $content;
    }
    //注册插件
    $_smarty->registerPlugin('block','nocache', 'smarty_block_nocache', false);
    
    //清除所有缓存
    //$_smarty->clearAllCache();
    
    //引入模板,多重缓存时要加上第二个参数(可以有多个参数)
    //$_smarty->display('cache.tpl', $_id);//多重缓存时也可以将URL中的参数全部传给后面的参数
    $_smarty->display('cache.tpl', $_SERVER["REQUEST_URI"]);
    
    ?>

    cache.tpl

    <!doctype html>
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    		<title>缓存机制</title>
    	</head>
    <body>
    
    Smarty的的多重缓时存获取参数:<br />
    {$id}
    <br />
    ----------------------<br />
    
    开启缓存后,让部分代码不缓存(利用自定义函数):<br />
    {'0'|date_format:'%Y-%m-%d %H:%M:%S'}<br />
    {nocache}
    	{'0'|date_format:'%Y-%m-%d %H:%M:%S'}
    {/nocache}<br />
    ----------------------<br />
    
    </body>
    </html>

    效果展示:


    如果访问http://127.0.0.1/smarty/cache.php?id=1&page=1,则会自动生成如_smarty_cache_php_id_1_page_1^de087441c95bd03a91d833c6b344eb35bda77af9.cache.tpl.php的缓存文件。


    相信大家掌握了这些,基本就可以在项目中使用Smarty了,更深入的研究就留给你们自己吧!




    *************************************************************

    PHP开发交流QQ群:127255239    验证消息:smcsdn

       群成员有限,先到先得会员资格,请认真填写验证消息

      资源都在这里,你还在到处闲逛什么呢?

      大神都在这里,你还在到处闲逛什么呢?

    *************************************************************


  • 相关阅读:
    49. 字母异位词分组
    73. 矩阵置零
    Razor语法问题(foreach里面嵌套if)
    多线程问题
    Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
    How to execute tons of tasks parallelly with TPL method?
    How to sort the dictionary by the value field
    How to customize the console applicaton
    What is the difference for delete/truncate/drop
    How to call C/C++ sytle function from C# solution?
  • 原文地址:https://www.cnblogs.com/oldinaction/p/5167456.html
Copyright © 2011-2022 走看看