`
dcj3sjt126com
  • 浏览: 1827362 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

smarty笔记

    博客分类:
  • PHP
阅读更多

 

smarty的常用功能及配置

 

配置使用部分:

 

# 修改默认的定界符

默认的定界符为{},可以在/includes/smarty_config.php中加入:

$tpl->left_delimiter = "<?";

$tpl->right_delimiter = "?>";

这样就把定界符改为了<? ?>

 

 

#debug的方法

    1.临时调试方法,在/includes/smarty_config.php中加入下行,

     把$tpl->debugging_ctrl = 'URL';

     然后在你正常访问的url中加入?SMARTY_DEBUG,如:

     http://test/smarty_test/test_tpl.php?SMARTY_DEBUG

     这样就会弹出调试窗口了。

     注意:$tpl->debugging这时要为默认值false;

     注意: url传入?SMARTY_DEBUG时当页有效(不设cookie)

        当传入?SMARTY_DEBUG=on时可以一次启动debug(用cookie)以后不传?SMARTY_DEBUG这时也可以调试

        当传入?SMARTY_DEBUG=off时删除cookie,去消debug

    2.在/includes/smarty_config.php中加入下行:

      $tpl->debugging = true;

      这时你打开任何页都会有debug窗口了。

    3.用在tpl文件中加入{debug}可以调试,调试弹出的内容与第2种方法大致一样,只有include文件一项在第3种方法中不包含现在现在用的,而第2种包括

    4.同时使用第2种与第3种或第1种与第3种,这样smarty的内置的很多内容都会显示出来,这个显出的内容最详细。

 

 

#注释的写法

 在左定界符的右边加*,在右定界符的左边加*

 默认为{* this is comment *}

 自定义定界符为<??>后,为<?* this is comment *?>

 

 

 

 

变量处理部分:

 

# 调用cookie/session/post/get里面的值。

 $smarty->request_use_auto_globals = true时(默认为true)

 可以在模板里通过{$smarty.get.varname}{$smarty.post.varname}这样调用

 

# 进行数学运算

 在php里: $tpl->assign("num",'1'); 或  $tpl->assign("num",1); 都可以。

 1.{assign var="tmp1" value="`$num+5+3*2`"} 引用 {$tmp1}

 2.{$num+1} 

 注意:{$num++} {$num--}不支持

 

#字符串处理格式 可以多级使用:如 {$articleTitle|lower|truncate:30|spacify} 

 

 使每个单词的第一个字母大写

 {$articleTitle|capitalize}

 

 字符串长度

 {$articleTitle|count_characters}

 

 字符串连接

 {$articleTitle|cat:$other_str}

 

 时间格式

 在php中: date_default_timezone_set("Asia/Shanghai");//用来设置时区

 $tpl->assign("now",time());

 {$now|date_format:"%Y-%m-%d %H-%M-%S"}

 

 默认值

 {$xxx|default:"no"} 只有在$xxx为null或''时才有用,其它值都没有用,array()也不行。

 

escape

 {$articleTitle|escape:"html"} 转成特殊字符转成html实体。

 {$articleTitle|escape:"url"}转成url的编码。

 

 字符大小写

 {$articleTitle|lower}

 {$articleTitle|upper}

 

 把串中的回行变<br>,对应php函数nl2br

 {$articleTitle|nl2br}

 

 字符串替换

    {$articleTitle|regex_replace:"/[\r\t\n]/":"LOVE"} 正则

    {$articleTitle|replace:"film":"LOVE"}  

 

 字符串格式 对应php函数sprintf

    {$articleTitle|string_format:"%s kkkk"}

    {$number|string_format:"%.2f"}

    {$number|string_format:"%d"}

 

 把字符串中的空白字符去掉换成单个空格(或别的字符如&nbsp;)

 {$articleTitle|strip}

 

 把串中的html标签换成空白或去掉

 {$articleTitle|strip_tags:false}

 

 截取字符串(对中文最后会有乱码)

 {$articleTitle|truncate:30}

 

 段落数目

 {$articleTitle|count_paragraphs}

 句子数(对中文意义不大)

 {$articleTitle|count_sentences}

 单词数(对中文意义不大)

 {$articleTitle|count_words}

 段落缩排

 {$articleTitle|indent:10}

 插空,在字母之间加入指定字符,对汉字无效果

 {$articleTitle|spacify:'-'}

 包裹串,把一个串按每行30个字符回行(可以定义回行符)

 {$articleTitle|wordwrap:20}

 

 

函数部分

  使用方法:{func var="test" var1="test1" ......}    

           func为函数名,var入参名,"test"为入参值   

  入参中有变量的写法:

       {func var="test`$foo.bar`test"} 请用``引起来。如果两边有空格不加``也可以。

       {func var="test`$foo`test"}

 

#内置函数:

   foreach循环:

   php: $tpl->assign('arr',array("a"=>'pig',"b"=>'cat',"c"=>'dog','d'=>'fish'));

   模板:

      <ul>

      {foreach name=animals from=$arr1 key=_key item=_item}

        <li>{$smarty.foreach.animals.index}

            | {$smarty.foreach.animals.iteration}=>

            {if $smarty.foreach.animals.first }

            <b>{$_key}: this is a {$_item}!</b>

            {elseif $smarty.foreach.animals.last}

            <i>{$_key}: this is a {$_item}!</i>

            {else}

            {$_key}: this is a {$_item}!

            {/if}

        </li>

      {foreachelse}

        <li>i am wrong!</li>

      {/foreach}

        <li>totol: {$smarty.foreach.animals.total}</li>

        <li>show: {if $smarty.foreach.animals.show} 1 {else} 0 {/if}</li>

        </ul>

   $smarty.foreach.animals.show:当from的值为空时,它为false,否则为true.

   {foreachelse}:               当from的值为空时,显示{foreachelse}之后的内容。

   $smarty.foreach.animals.iteration: 当前循环序号,它是从序号1开始的。

   $smarty.foreach.animals.first:当是循环到第一次时为true,其它为false;

   $smarty.foreach.animals.last:当是循环到最后一次时为true,其它为false;

   $smarty.foreach.animals.index:当前的循环序号,它是从0开始的。

 

   section循环,可以处理多级数组,但第一级数组的key值一定要是自然序列0,1,...

   php中:

    $tpl->assign('names',array('zhang hua','li meing','xu zi','hong li'));

    $tpl->assign('ages',array(array('age'=>22),array('age'=>13),array('age'=>22),array('age'=>21)));

    $tpl->assign('grades',array('2','4','6','3'));

    {section name=sec_index loop=$names}

        no: {$smarty.section.sec_index.index}<br>

        name: {$names[sec_index]}<br>

        ages: {$ages[sec_index].age}<br>

        grades: {$grades[sec_index]}<br><hr><br>

    {/section}

  说明:

  $smarty.section.customer.total 总数

  $smarty.section.customer.show 是否可显示

  $smarty.section.customer.iteration 当前循环号,行号 从1开始

  $smarty.section.customer.rownum 行号 从1开始

  $smarty.section.customer.first 是否是第一个元素

  $smarty.section.customer.last 是否是最后一个元素

  $custid[customer.index]  前当元素

  $custid[customer.index_next] 后一个元素

  $custid[customer.index_prev] 前一个元素

  $smarty.section.customer.index 循环index,从0开始

  sectionelse 同foreachelse 

   从0开始,循环到10,步长为1

   <{section loop=10 name=n start=0 step=1}>

    <div class="mt5">

     -<{$smarty.section.n.index}> 从0开始的循环序号.

     -<{$smarty.section.n.iteration}> 从1开始的循环序号.

     -<{$smarty.section.n.first}>- 每一次循环时为true.

     -<{$smarty.section.n.last}>-  最后一次循环时为true.

    </div>

   <{/section}>

 

 

  引用别的模板文件

  例如:{include file="header.tpl" assign1="value1" assign2="value2" ....}

  {include file=#includeFile#} includeFile在配置文件里设置

  {include file="$file"}

  {include file="inc.tpl" assign="inc"} 把include文件的内容赋值给变量$inc,然后调用{$inc}

 

  加载配置文件

  例如:

  1. (全局的情况下)先在config文件夹里建立一个tea_config.txt文件,里面写入:

  pageTitle = "This is mine"

  bodyBgColor = "#eeeeee"

  在模板里写入:

    {config_load file="tea_config.txt"}

  2.(有section的情况下)先在config文件里写入

    [Login]

    uname = "Login uname"

  在模板里写入:

  {config_load file="tea_config.txt" section="Login"}

  {#uname#}

  注意:在load一个section时全局变量也会被引入,如果两个变量同名,那section中的变量会覆盖全局的,如果两个全局变量同名则,则后一个值覆盖前一个值

 

  调用php文件(不推荐用)

  {include_php file="inc.php"} 

 

  insert的用法

  在模板中: {insert name="print_arr" lid=$user_name sid="$arr"}

  在php文件中:

  function insert_print_arr($arr)

  {//在这里可以得到name,lib,sid为键与对应值的数组$arr,return的东西可以在模板中insert的信息输出

    return "<pre>".var_export($arr,true)."</pre>";

  }

 

  数据块内的数据可以避免被模板解析,可以用于写入js,css等内容

  {literal}

    <script type="text/javascript">。。。。

    </script>

  {/literal}

 

  在{strip}{/strip}之间的html代码在输出前会把所有的多余的空白,还有回行符号去掉

 

  在模板里直接用php语法。

  {php}

   echo "xxxx0000";

  {/php}

 

  输出缓冲区,在{capture}{/capture}之间的块不会输出,而会把值赋给变量$smarty.capture.div1

  {capture name="div1"}

    <div>

        <b>name: </b>{$user_name}<br>

        <b>age: </b>{$age}<br>

    </div>

  {/capture}

  调用方法:{$smarty.capture.div1}

 

定制函数

 

   设置临时变量

   {assign var="peple_count" value="212222"} {$peple_count}

 

 

   counter输出数字,下面的例子会输出0,3,6,9

    {counter start=0 skip=3}<br />

    {counter}<br />

    {counter}<br />

    {counter}<br />

 

   循环改变单元格的颜色

        style="color:{cycle values="#eeeeee,#d0d0d0"}"

 

   eval把引用串内的模板标识解析后显示,里面可以用各种变量、config文件中的引用变量都可以动态的替换成最终显示串

   如 $tpl->assign("user_name","francis");

      $tpl->assign("other_name",'{$user_name}');

   模板 {eval var="$other_name"}

   输出 francis

 

   fetch加载另一个文件的内容到此文件,如

    <script type="test/javascript">

    {fetch file="http://www.sohu.com/sohuflash_1.js"}

    </script>

 

   html_checkboxes多选框:

   $tpl->assign('children', array( 

            1000 => 'Joe Schmoe', 

            1001 => 'Jack Smith', 

            1002 => 'Jane Johnson', 

            1003 => 'Charlie Brown')); 

   $tpl->assign('children_select', array(1000,1002));

   {html_checkboxes name="childrens"options="$children" selected="$children_select" separator="&nbsp;"}

 

  html_radio 单选框

   $tpl->assign('children', array( 

            1000 => 'Joe Schmoe', 

            1001 => 'Jack Smith', 

            1002 => 'Jane Johnson', 

            1003 => 'Charlie Brown')); 

   $tpl->assign('children_select1', 1002); 

   {html_radios name="children_chk" options=$children selected=$children_select1 separator="<br>"}

 

   children_select下拉菜单

   $tpl->assign('children', array( 

            1000 => 'Joe Schmoe', 

            1001 => 'Jack Smith', 

            1002 => 'Jane Johnson', 

            1003 => 'Charlie Brown')); 

   $tpl->assign('children_select1', 1000); 

    <select name="good_student">

    {html_options options="$children" selected="$children_select" }

    </select>

 

   html_select_date选则日期

   {html_select_date prefix="kill_"}

 

   html_select_time选则时间

   {html_select_time  prefix="kill_"}

 

   html显示图片

   {html_image file="http://www.baidu.com/img/lm.gif" width=40 height=40}

 

   html_table把数组在一个表格里输出,这个数组的键值必须是自然序列0,1,2...

   {html_table loop=$data}

 

   math数学运算

   {math equation="(( x + y ) / z )" x=2 y=10 z=2}

 

   mailto为email加mailto标签

   {mailto address="me@example.com"}

 

   popup鼠标放上后的小提示 overlib从

   {popup_init src="http://fengzheng369.blog.163.com/blog/./overlib.js"}

   <a href="http://fengzheng369.blog.163.com/blog/mypage.html" {popup text="This link takes you to my page!"}>mypage</a>

 

   textformat删除串中空白字符,格式化字符串(不常用)

   {textformat wrap=40 indent=4 indent_first=4}

 

   为smarty增加function插件

   在smarty的plugins文件夹下放入下列文件function.pr.php

   注意:此文件可以放在smarty系统的plugins文件夹也可以自定义文件夹,只需要在smarty的配置文件中加入你的文件夹路径:

   $tpl->plugins_dir     =  array($cur_dir."smarty/plugins",$cur_dir."my_plugins");

   就行了:)

    <?php

    function smarty_function_pr($params, &$smarty)

    { 

        $tg_arr = $params['var'];

       return "<pre>".var_export($tg_arr ,true)."</pre>"; 

    } 

    ?>

   在模板中写入:

    {pr var="$ages"}

 

  为smarty增加modifier插件

  在你的plugin文件目录或smarty的plugin目录下建立modifier_truncatecn.php

      <?php

    function smarty_modifier_truncatecn($string, $length = 80, $etc = '...')

    { 

        if ($length == 0) 

                return ''; 

 

        if (mb_strlen($string,"utf-8") > $length) { 

                $length -= mb_strlen($etc,"utf-8"); 

                $fragment = mb_substr($string, 0, $length+1,"utf-8"); 

                return $fragment.$etc; 

        } else 

            return $string; 

 

    } 

     ?>

   在模板文件里你就可以用{$a_pig|truncatecn:6:"。。。"}来截取中文字串了

 

 

   为smarty增加block插件

   在你的plugin文件目录或smarty的plugin目录下建立block.bold.php

    <?php

    //$repeat 为true时表示是开始标签,$repeat为false时表示结束标签

    function smarty_block_bold($params, $content, &$smarty, &$repeat)

    { 

        if($repeat==false && $content !="")

        {

         return "<b>".$content."</b>";

        }

    }

    ?>

  然后你就可以用{bold}...{/bold}了。

 

  为smarty增加编译插件

  1.增加固定的编译插件,在你的plugin文件目录或smarty的plugin目录下建立compliler.tplheader.php

    <?php

    function smarty_compiler_tplheader($tag_arg, &$smarty) 

    { 

        return "\necho '"."<!--". $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "-->\n"."';"; 

    } 

    ?>

    {tplheader}

  2.增加动态的编译插件,所谓动态是指在程序的执行的过程可以根据具体情况变化插件的执行内容。

   在php文件中写入函数:

    function dyn_comp_func($tag_arg, &$smarty)

    {

          return "\necho '"."<!--". $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "fromhere-->\n"."';"; 

    }

      然后注册这个函数:

      $tpl->register_compiler_function("dyn_comp_biaoqian","dyn_comp_func",false);

      最后就可以在模板文件内引用:

      {dyn_comp_biaoqian} 这里也可以传入参,但传入的参灵敏并不会以数组交给dyn_comp_func的$tag_arg,而是以串的形式传过去。

 

  为smarty增加编译前处理程序插件/编译后处理插件

  在php中:

  function prefilter_pre01($source, &$smarty) 

  { 

     return  'i love you!!{$user_name}'.$source;

  } 

  然后注册成编译前处理程序插件

  $tpl->register_prefilter("prefilter_pre01"); 

 

  为smarty增加输出过滤插件

  在php中

  function outputfilter001($output, &$smarty) 

  { 

     return $output." i am out!";

  } 

  然后注册:

  $tpl->register_outputfilter("outputfilter001");

 

  为smarty增加db资源,或修改默认的file模板

  php中

    function db_get_template($tpl_name, &$tpl_source, &$smarty) 

    { 

         $tpl_source = "this is a db content";

         return true; 

    } 

    function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty) 

    { 

        return time();

    } 

    //这个函数仅用于模板资源 在db资源中无用

    function db_get_secure($tpl_name, &$smarty) 

    { 

        echo "$tpl_name";exit;

        return false; 

    } 

        //此函数是供include_php}或 {insert}使用的 在db资源中无用

    function db_get_trusted($tpl_name, &$smarty) 

    { 

        return false;

    } 

    $tpl->register_resource("db", array("db_get_template", 

    "db_get_timestamp", 

    "db_get_secure", 

    "db_get_trusted")); 

  模板中:

       {include file="db:inc.php"}

  默认的file:xx.php(与xx.php一样)文件也可以更改,请自定义函数并用smarty->default_template_handler_func指定就可以了。

 

 

  向smarty注册类调用

  在php中:

  class My_Object { 

    function add($params, &$smarty_obj) { 

        return $params['a']+$params['b']; 

    } 

  } 

  $myobj = new My_Object;

  $tpl->register_object("obj",$myobj);

  在模板中

  {obj->add a="3" b="5"}//将会输出8

 

 

  自己定制cache处理函数

    function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null, $exp_time=null) 

    { 

        $return='';

        switch ($action) { 

        case 'read': 

            // read cache from database 

 

            break; 

        case 'write': 

            // save cache to database 

 

            break; 

        case 'clear': 

            // clear cache info 

 

            break; 

        default: 

            // error, unknown action 

 

            break; 

        } 

        return $return; 

 

    } 

   //启用它

   $tpl->cache_handler_func = 'mysql_cache_handler';

 

   缓存的使用

   $tpl->caching = 1;//或=2都是使用缓存

   缓存失效时间是$tpl->cache_lifetime控制的,默认为3600,一个小时。

   在显示时可以为template指定cache_id,这样当这个template在别的地方使用时再指定一个别的cache_id,这样生成的多个缓存文件,各不影响。

   如:

   $tpl->display("test.tpl","test_tpl");

   要清空时:$tpl->clear_cache("test.tpl","test_tpl"); 每次清空只会清空与display显示时参数一样的cache文件,而不会对其它cache产生影响。

 

<p>{$str1|strlen}</p>

<p>{$str2|strpos:'is'}</p>

 

# 显示时间.

<{$row.created_date|date_format:"%Y-%m-%d %H:%M:%S"}> 

当时时间:

<{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}> 

<{"`$smarty.now+24*3600`"|date_format:"%Y-%m-%d"}>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics