smarty模板基礎

將前臺後臺隔離,前臺控制顯示,後臺控制邏輯/內容,與cms相似
原理: 用戶訪問text.php頁面,後臺調用類smarty.class.php顯示靜態模板;
臨時文件:
在不改變模板內容的狀況下,再次訪問頁面,直接從臨時文件獲取,不走smarty.class.php,提升加載速度;當改變了模板內容,就得從頭來過。
緩存文件:
相比臨時文件,裏面放的是html文件,運行效率更快;通常需設置有效期,不設置的話,當數據庫內容改變時,再次刷新頁面,頁面顯示內容無變化,由於執行的是緩存。
 
smarty.class.php(核心):
<?php
class Smarty
{
    public $left="<{";  //左分隔符
    public $right="}>"; //右分隔符
    public $attr=array(); //存儲變量
    
    //註冊變量
    function assign($name,$value)
    {
        $this->attr[$name]->$value;
        }
    //顯示模板
    function display($filename){
        //獲取靜態文件內容
        $str=file_get_contents($filename);
        
            /*<html>        
            <head></head>
            <body>
            <div><{aa}></div>
            </body>
            </html>
            */
            //獲得結果
            
        //正則表達式匹配內容,aa,查找和替換
            /*<html>        
            <head></head>
            <body>
            <div><?php echo $attr["aa"] ?></div>
            </body>
            </html>
            */
            //獲得結果
        //將替換後的內容存到臨時文件
        $lujing="../text/docunment.php";
        file_put_contents($lujing,$str);
        //讀取臨時文件
        include ($lujing);
        }
    }

配置文件int.inc.php(核心):php

<?php
define("ROOT",str_replace("\\","/",dirname(__FILE__)).'/'); //常量ROOT中指定項目根目錄

//echo str_replace("\\","/",dirname(__FILE__)).'/'; //獲取當前文件所在的位置

require ROOT.'libs/Smarty.class.php'; //加載Smarty類文件
$smarty = new Smarty(); //實例化Smarty對象


//$smarty -> auto_literal = false; //就能夠讓定界符號使用空格
$smarty->setTemplateDir(ROOT.'templates/'); //設置全部模板文件存放位置
//$smarty->addTemplateDir(ROOT.'templates2/'); //添加一個模板文件夾
$smarty->setCompileDir(ROOT.'templates_c/'); //設置編譯過的模板存放的目錄
$smarty->addPluginsDir(ROOT.'plugins/'); //設置爲模板擴充插件存放目錄
$smarty->setCacheDir(ROOT.'cache/'); //設置緩存文件存放目錄
$smarty->setConfigDir(ROOT.'configs/'); //設置模板配置文件存放目錄

$smarty->caching = false; //設置Smarty緩存開關功能
$smarty->cache_lifetime = 60*60*24; //設置緩存模板有效時間一天

$smarty->left_delimiter = '<{'; //設置模板語言中的左結束符
$smarty->right_delimiter = '}>'; //設置模板語言中的右結束符
?>

 main.php:html

<?php
include("../init.inc.php");
$smarty->assign("aa","hello");
$smarty->display("test.html")
相關文章
相關標籤/搜索