smarty框架

Smary是用来将表现和内容相分离的框架

smary的原理

  class Smarty{
      private $tpl_var=array();
      public function assign($k,$v){
          $this->tpl_var[$k]=$v;
      }
    
      public function compile(){
          $str=file_get_contents('./demo.html');                                   //将文件的内容转换为字符串
          $str=str_replace('{','<?php echo $this->tpl_var["',$str);        //将文件中所有的{  转换为  <?php echo
          $str=str_replace('}','"];?>',$str);                                            //将文件中所有的}  转换为 ?>
        
          file_put_contents('./demo.html.php',$str);                             //混编文件
        
          require './demo.html.php';

      }
  }

优化代码

  //如果混编文件存在,并且混编文件的修改时间大于模板修改时间,则直接引入。否则重新生成。

  file_exists($compile_path) && filemtime($compile_path) > filemtime($tpl_path)

优化文件结构

  //新建一个模板文件夹(view,template),和编译文件夹(view_c,template_c),用来存放对应的文件

  templates:默认存放模板文件夹

  templates_c:默认存放混编文件的文件夹

  cache:存放缓存

  configs:存放配置文件

注释

  {*这是注释*}

  Smarty注释和HTML注释的区别

声明变量

  require './Smarty/Smarty.class.php';
  $smarty=new Smarty();
  $smarty->assign('title','锄禾');

  {assign var = '变量名' value='值' }

取值

  {$name}

保留变量

  在Smarty中有一个特殊的变量“smarty”,这个变量是保留变量,用来访问用户请求的信息,系统环境变量,常亮,类似于PHP中的超全局变量。

  1. 获得get提交的值:例如:{$smarty.get.name}       $_GET
  2. 获得post提交的值                  {$smarty.post.变量名}    $_POST
  3. 万能的获得值的方法      {$smarty.request.变量名}  $_REQUEST
  4. 获取会话: 在PHP中定义一个会话

在html中写,css或js时

  在{}中加 空格

smarty对数组的访问

  1. 数组[下标]
  2. 数组.下标

foreach

  如果不存在遍历的数组则执行{foreachelse}部分

判断

  {if  条件}

 

  {elseif  条件}

 

  {else}

 

  {/if}

循环

  只支持索引数组,不支持关联数组。

  {section  name='自定义变量名'  loop='被遍历的数组'}

         {数组['自定义变量名']}

  {/section}

for循环

 {for $i = 1 to  10}{/for}

while循环

  {assign var= "i" value=1}

  {while $i<10}

  {/while}

值变量@iteration

1开始的序号

值变量@index

0开始的索引

值变量@first

判断是否是第一个元素

值变量@last

判断是否最后一个元素

值变量@total

数组的长度

值变量@show

数组是否为空

原文地址:https://www.cnblogs.com/diverman/p/8711330.html