zoukankan      html  css  js  c++  java
  • smarty模板基础

     1、什么是smarty?

    Smarty是一个使用php写出来的模板引擎,它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与html代码混杂在一起PHP代码逻辑分离。

    2.smarty的工作原理:

    <?php
        class Smarty
        {
            public $left="{";  //左分割符
            public $right="}";
             
             
            //所有后台数据要存在这个数组里;
            public $arr =array();
             
             
            //注册变量(将这个变量写到数组里存一下),将得到的数据传到上面的数组中
            public function assign($name,$value){
                $arr[$name] = $value;
            }
             
             
            //显示模板(核心)(看下图)
            public function display($url){
                 
                //找到模板文件
                $str = file_get_contents($url);
                 
                //根据正则匹配带有标记({})的内容,做替换
             
                //将编译好的文件缓存下来          
                file_get_contents("",$str);
             
                //将文件拿到当前页面显示
                include();
     
            }
         
        }
         
         
     
     
    ?>
      

    看一下smarty原理图:

    3.smarty使用示例:

    <?php
        //引入smarty类
    require "../init.inc.php";
     
    //数组类型
    $arr =array("one"=>"1111","two"=>"2222");
     
    //对象
    class Ren{
        public $name="张三";
    }
    $r= new Ren();
     
    //注册变量
    $smarty->assign("ceshi","hello");  //字符串
    $smarty->assign("shuzu",$arr);  //数组
    $smarty->assign("duixiang",$r);  //对象
     
    //显示
    $smarty->display("test.html");
    ?>

    test.html页面:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    </head>
     
    <body>
    <{$ceshi}>
    <{$shuzu["one"]}>
    <{$duixiang->name}>
    </body>
    </html>

    这样就能显示效果了:

  • 相关阅读:
    牛客前缀和题、枚举---[HNOI2003]激光炸弹
    牛客贪心题---拼数
    牛客枚举题---明明的随机数
    牛客模拟、差分题---校门外的树
    牛客贪心题---纪念品分组
    03_7_继承和权限控制
    03_6_package和import语句
    03_5_static关键字
    01_8_sql主键生成方式
    01_7_模糊查询实体对象
  • 原文地址:https://www.cnblogs.com/mengshenshenchu/p/7102505.html
Copyright © 2011-2022 走看看