zoukankan      html  css  js  c++  java
  • Smarty模板引擎 学习记录

     
     
     
     
      
      require_once('../smarty/Smarty.class.php');
      $smarty=new Smarty();
      //smarty口诀:五配置两方法
      //五配置的介绍
      $smarty->left_delimiter="{";//左定界符
      $smarty->right_delimiter="}";//右定界符
      $smarty->template_dir="tpl"; //html 模板的地址
      $smarty->compile_dir="template_c"; //模板编译生成的文件
      $smarty->cache_dir="cache"; //缓存
      //下面是开启缓存的两个配置
      $smarty->caching=true; //开启缓存
      $smarty->cache_lifetime=120; //缓存时间
     
    方法使用:
    1.
    void assign (string varname, mixed var)
    用来赋值到模板中。可以指定一对 名称/数值 ,也可以指定包含 名称/数值 的联合数组。
     
    // passing name/value pairs 名称/数值 方式
    $smarty->assign("Name","Fred");
    $smarty->assign("Address",$address);

    // passing an associative array 联合数组方式
    $smarty->assign(array("city" => "Lincoln","state" => "Nebraska"));
     
    2.
    void display (string template [, string cache_id [, string compile_id]])
    显示模板,需要指定一个合法的模板资源的类型和路径。你还可以通过 第二个可选参数指定一个缓存号。 通过第三个可选参数,可以指定一个编译号。这在你想把一个模板编译成不同版本时使用,比如针对不同的语言编译模板。编译号的另外一个作用是,如果你 有多个$template_dir模板目录,但只有一个$compile_dir编译后存档目录,这时可以为每一个$template_dir模板目录指 定一个编译号,以避免相同的模板文件在编译后会互相覆盖。相对于在每一次调用display()的时候都指定编译号,也可以通过设置$compile_id编译号属性来一次性设定。
    display 例子 显示
    include("Smarty.class.php");
    $smarty = new Smarty;
    $smarty->caching = true;

    // only do db calls if cache doesn't exist
    // 只有在缓存不存在时才调用数据库
    if(!$smarty->is_cached("index.tpl"))
    {

     // dummy up some data
     $address = "245 N 50th";
     $db_data = array(
            "City" => "Lincoln",
         "State" => "Nebraska",
       "Zip" = > "68502"
            );

     $smarty->assign("Name","Fred");
     $smarty->assign("Address",$address);
     $smarty->assign($db_data);

    }

    // display the output
    // 显示输出
    $smarty->display("index.tpl");
     
    3.
    tpl变量调节输出:
    ①{$var|capitalize} //首字母大写
    ②{$var|cat:'string'}//字符串连接符(:相当于.)
      {$var|cat:'string1':'string2'}// 要输出多个字符串只需:'srting'即可
    ③{$time|date_format:"%H:%M:%S"}  //date_format(time,format) 而date(format,time)
    ④{$var|default:'content'}  //将$var的默认值指定为content(不管var是否有值)
    ⑤{$var|escape:'url'}  //将var转码为URL模式(后面''里指定转码模式)
    ⑥{$url|lower} {$url|upper}  //前面的将变量全部变为小写,后面的全部为大写
    ⑦{$var|nl2br}  //因为HTML不能识别换行符,这条语句将变量字符串里的换行符转换为<br/>
     
    例子:
    //test.php
    $smarty->assign('score','91');
     
    //test.tpl
    {if $score gt 90}
        优秀
    {elseif $score gt 60}
        合格
    {else}
       不及格
    {/if}
     
    循环方式
    //test.php
     
    $articlelist=array(
                    array("title"=>"第一篇文章","author"=>"小J","content"=>"第一篇文章内存"),
                    array("title"=>"第二篇文章","author"=>"小L","content"=>"第二篇文章内存"),
                    );
      $smarty->assign('articlelist',$articlelist);
      $smarty->display('test.tpl');
     
    //test.tpl
    循环方法一:
    {section name=article loop=$articlelist}  
            {$articlelist[article].title}
            {$articlelist[article].author}
            {$articlelist[article].content}
    <br/>
    {/section}
    section属性
    name:(必选) section循环的名称只是标示循环唯一的名字没有特别意义,前面没有 $符号;
    loop: (必选)是在php声明中的变量名称,用来标示是循环哪一个数组(即要循环数组名)需要使用 $
    start: (可选)循环执行的初始位置 . 如果该值为负数,开始位置从数组的尾部算起 . 例如:如果数组中有7个元素,指定 start-2 ,那么指向当前数组的索引为 5. 非法值( 超过了循环数组的下限 )将被自动调整为最接近的合法值 .
    step: (可选)如其它语言的循环,是一个步长,如果为负数,则倒序循环;
    max:(可选)循环的最大下标,如果是 1则只循环1 次,如果为 2则循环2次;
    show:(可选)默认为true即显示。如果设置了 {sectionelse}。表示如果数组没有内容的时候显示这部分的内容;如果 showfalse 则显示这部分。如果没有设置 {sectionelse}则不输出该数组。
     
    循环方法二:
    {foreach $articlelist as $article}
            {$article.title}
            {$article.author}
            {$article.content}
    <br/>
    {/foreach}
     
    Smarty的引用
    ①{include file='header.tpl'} //输出header.tpl文件内容
    ②{include file='header.tpl' sitename='content'}  //content 代替header.tpl文件中的 {$stitename}
     
    Smarty类和对象赋值
    /*在test.php 中定义且实例化的类,传给test.tpl后,它可以做直接对类的方法等直接使用 */
    //test.php
     
     class My_object{
         function meth1($pam){
               return $pam[0].'个'.$pam[1];
            }
       }
      $my_obj=new My_object();
      $smarty->assign('my_obj',$my_obj);
      $smarty->display('test.tpl');
     
    //test.tpl
    {$my_obj->meth1(array('你是','好人'))}   //网页输出:你是个好人
     
    Smarty函数的使用
    example 1:
     
    //test.php
    $smarty->assign('time',time());
    $smarty->display('test.tpl');
     
     
    /*对于函数使用,| 前的作为date函数的第一个参数,:后的作为第二个参数*/
    //test.tpl
    {"Y-m-d"|date:$time}  //output: 2016-03-10
     
    example 2:
    /*PHP函数 str_replace($str1, $str2, $str) 其中将字符串 str 中的 第一个参数 替换为 第二个参数*/
    //test.php
    $smarty->assign('str','asdfgh');
      $smarty->display('test.tpl');
     
    //test.tpl
    {'f'|str_replace:'k':$str} //将 str 中的 f 替换为 k
     
     
    example 3:
    //test.php
     function test($params){
         $p1=$params['p1'];
         $p2=$params['p2'];
         return '穿入的键值1的值为:'.$p1.',穿入的键值2的值为:'.$p2;
      }
     
    //注册函数插件类型为function,定义插件函数名为f_test,test为回调函数名称
      $smarty->registerPlugin('function','f_test','test');  
      $smarty->display('test.tpl');
     
    //test.tpl
    {f_test p1='hhhh' p2='kkkk'}  //将一个数组Array ( [p1] => hhhh [p2] => kkkk )回调给test.php中中test函数的参数$params
     
    //output
    穿入的键值1的值为:hhhh,穿入的键值2的值为:kkkk
     
     
     
    MVC:  C通过M获取数据,C又通过V将获取的数据输出,其中M是业务逻辑层是最核心的部分,如果发现自己的C层代码越来越多可能就没有很好的分清与M的分工
     
    example 1:    //function 函数插件
    //function.test.php
    function smarty_function_test($params){    //smarty_function_插件名(相当于C)
          $width=$params['width'];
          $height=$params['height'];
          $area=$width*$height;
          return $area;
      }
     
    //test.php
     $smarty->display('area.tpl');    //output:20000 (相当于V)
     
    //area.tpl
    {test width=100 height=200}  //$params获取area.tpl回调的数组(相当于M)
     
    example 2:    //modifiers 变量调节器插件
    //modifier.test.php
     
    function smarty_modifier_test($utime,$format){  
          return date($format,$utime);    //PHP的date(格式,时间戳)
     }
     
    //test.php
     
     $smarty->assign('time',time());  //获取本地时间戳
      $smarty->display('utime.tpl');  //输出
     
    //utime.tpl
    {$time|test:'Y-m-d H:i:s'}  //$time作为第一个变量传参给$utime,'Y-m-d H:i:s'传参给$format(区别:function传回的是数组)
     
     
    example 3:    // block functions区块函数插件(既可以像function传递数组又可以像modifier传递参数)且有闭标志
     
    //上面的提示说明,block再定义test函数会与function定义的test函数冲突,所以下面定义test1
     
    //block.test1.php
    function smarty_block_test1($params,$content){  //
        $replace=$params['replace'];
        $maxnum=$params['maxnum'];
        if($replace=='true'){
            $content=str_replace(',',',',$content);
            $content=str_replace('.','。',$content);
        }
        $str=substr($content,0,$maxnum);
        return $str;
      }
     
    //test.php
    $smarty->assign('str','Hello world,hello man and women,hell dog and pig.');
    $smarty->display('block.tpl');
     
    //block.tpl
    {test1 replace='true' maxnum=200}   //将数组传给$params
    {$str}        //$str 将值传参给 $content 
    {/test1}    //注意:这里有闭标志
     
    example 4:    //ORG第三方类库的自定义
     
    //function.php
     
     function C($name,$method){                   //实例化控制器函数
        require_once('/libs/Contorller/'.$name.'Controller.class.php');
        $controller=$name.'Controller';
        $obj=new $controller();
        $obj->$method();
      }
     
    //自定义第三方类库
    function ORG($path,$name,$params=array()){
    //path是路径,name是第三方类名
    //params是该类初始化时需要指定和赋值的类的属性,格式为array(属性名=》属性值.....) 
     
         require_once('libs/ORG/'.$path.$name.'.class.php');   //ORG是第三方插件类库
         $obj=new $name();
         if(!empty($params)){
             foreach($params as $key=>$value){
                 $obj->$key=$value;       //实例化对象属性值
             }
         }
        return $obj;
      }
     
    //config.php
    //把smarty的配置专门放到配置文件中
    $viewconfig=array('left_delimiter'=>'{','right_delimiter'=>'}','template_dir'=>'tpl','compile_dir'=>'template_c');  
     
     
     //index.php
      require_once('function.php');
      require_once('config.php');
      $view=ORG('Smarty/','Smarty',$viewconfig);   //把smarty的第三方类库和smarty类以及smarty配置变量都传递给ORG函数
      $controller=$_GET['controller'];
      $method=$_GET['method'];
      C($controller,$method);
     
    //testController.class.php
     
    class testController{
          function show(){
            global $view;
            $view->assign('str','哈哈哈哈');
            $view->display('test.tpl');
          }
      }
     
    //test.tpl
    {$str}
     
    //output:哈哈哈哈
     
     
  • 相关阅读:
    随笔:自我介绍与软工 5 问
    作业要求 20200924-1 每周例行报告
    作业要求20200924-2 功能测试
    作业要求 20200924-5 四则运算试题生成,结对
    作业要求20200924-3 单元测试,结对
    作业要求20200924-4 代码规范,结对要求
    20200929-git地址
    作业要求 20200917-3 白名单
    作业要求 20200917-1 每周例行报告
    20200917-2 词频统计
  • 原文地址:https://www.cnblogs.com/lantian00/p/5297227.html
Copyright © 2011-2022 走看看