Smarty的安裝

smarty是一個PHP模板引擎,用於區分美工與程序

可以在www.smarty.net官方網站下載,有smarty 2.X、smarty 3.X,smarty 3生成的編譯後的文件很大,暫時使用Smarty 2

Smarty/libs包含了核心文件


test.php

<?php

require('./libs/Smarty.class.php');//包含smarty類文件

$smarty = new Smarty;//創建smarty對象

$smarty->template_dir = './templates/';//指定模板文件所在位置
$smarty->compile_dir = './templates_c/';//指定編譯後的文件所在位置
$smarty->config_dir = './configs/';//指定配置文件
$smarty->cache_dir = './cache/';//緩存文件

$smarty->assign('name','ChuangRain');//分配變量

$smarty->display('index.html');//顯示templates/index.html
index.html
{* Smarty *}//註釋

hello,{$name}!//輸出 hello,ChuangRain

如果是現在這種{}標籤,js會出問題,因爲在js中會用到{},在smarty編譯時會將其當作是smarty要編譯的東西,會出錯。

例index.html

{* Smarty *}

hello,{$name}!

<script>

function test(){
	alert('11111111111111');
}

test();

</script>
運行時會出現下面的錯誤信息

Fatal error: Smarty error: [in index.html line 7]: syntax error: unrecognized tag: alert('11111111111111'); (Smarty_Compiler.class.php, line 446) in D:\AppServ\www\Smarty\libs\Smarty.class.php on line 1093

可以用literal來忽略{},

{literal}
    <script>
        function test(){
              ...
        }
    </script>
{/literal}
<!-- 在{/literal}和{/literal}之間的內容會被當作文本來處理,忽略其內容 -->

但是一般都是修改smarty的標籤,來解決這個問題

$smarty->left_delimiter = "<{";//左標籤 <{
$smarty->right_delimiter = "}>";//右標籤 }>

在模板中使用變量就可以直接用 <{$name}>



發佈了47 篇原創文章 · 獲贊 25 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章