zoukankan      html  css  js  c++  java
  • 夺命雷公狗---Smarty NO:23 常用方法

    • assign :分配变量到模板文件(值传递)
    • assignByRef:分配变量到模板文件(引用传递)

    assignByRef代码示例:

    $smarty = new Smarty();
    $name = ‘lisi';
    //$smarty -> assign(‘name’,$name);  值传递相当于把lisi复制一份发送到模板页
    $smarty -> assignByRef(‘name’,$name);//引用传递,把$name变量的首地址赋值给模版页
    $smarty -> display(‘demo7.html’);

    append :分配变量到模板数组变量中

    示例:

    <?php
    require “smarty/Smarty.class.php”;
    $smarty = new Smarty();
    $city = ‘北京';
    //通过append方法分配变量到模版文件
    $smarty -> append(‘city’,$city);
    $smarty -> display(‘demo7.html’);

    改写分页程序,如下所示:

    $sql = “select id,name,age from stu order by id desc limit $offset,$pagesize”;
    $res = mysql_query($sql);
    $data = array();
    while($arr = mysql_fetch_assoc($res)){
    //$data[] = $arr;
    $smarty -> append(‘data’,$arr);
    }
    //通过assign方法分配变量到模版文件
    //$smarty -> assign(‘data’,$data);//遍历出来的结果
    $smarty -> assign(‘pagecount’,$pagecount);//总页数
    • appendByRef:分配变量到模板数组变量中(引用传递)
    • clearAllAssign:清除所有分配到模板中的变量
    • clearAssign:清除指定的模板变量
    • clearCache:清除缓存
    • configLoad:载入配置文件

    引入配置文件如下所示

    <?php
    require “smarty/Smarty.class.php”;
    $smarty = new Smarty();
    $smarty -> configLoad(“config.conf”);
    $smarty -> display(‘demo7.html’);
    • clearConfig:清除配置变量信息
    • display:显示输出模板信息,如下所示

    $smarty -> display(‘demo7.html’);

    • fetch:载入文件到字符串

    demo7.php代码示例:

    <?php
    require “smarty/Smarty.class.php”;
    $smarty = new Smarty();
    $title = ‘test';
    $smarty -> assign(‘title’,$title);
    $str = $smarty->fetch(‘demo7.html’);
    echo $str;

    demo7.html代码示例:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=’utf-8′>
    <title></title>
    <script src=”jquery.js”></script>
    </head>
    <body>
    {$title}
    </body>
    </html>

    在实际项目开发中,fetch拥有非常广泛的用途,例如静态化技术

    //display有两个功能,1.载入到字符串   2.输出字符串echo
    $str = $smarty->fetch(‘demo7.html’);

    file_put_contents(“html/”.time().’.shtml’,$str);

    • templateExists :判断当前模板文件是否存在

    示例代码如下:

    <?php
    header(“Content-Type:text/html;charset=utf-8″);
    require “smarty/Smarty.class.php”;
    $smarty = new Smarty();
    $title = ‘test';
    $smarty -> assign(‘title’,$title);
    if($smarty->templateExists(“demo79.html”)){
        $smarty -> display(“demo7.html”);
    }else{
        echo “系统正在维护中,稍后会为您提供更好的服务…”;
    }
  • 相关阅读:
    数组的一些经典案例(循环)(max=score[0])(冒泡)(flag标志)(杨辉三角)
    冒泡排序
    C语言之数组
    循环结构的一些案例:倒等腰三角形、菱形、暴力破解
    break和contine关键字
    循环嵌套(打印*** ***)
    循环的经典案例(李白买酒)
    C语言循环结构-while/do...while/for--逢3过,阶乘,九九乘法表
    WordPress部署踩坑记
    Symbol
  • 原文地址:https://www.cnblogs.com/leigood/p/5033481.html
Copyright © 2011-2022 走看看