模板引擎的作用是什么
對PHP語言熟悉的程序員就會知道有個Smarty的名詞厕妖,那么這個具體是什么呢沪蓬?smarty是一個使用PHP編寫的PHP模板引擎揭芍,是目前業(yè)務(wù)最著名眨唬,功能最強(qiáng)大的一種PHP模板引擎,程序邏輯邏輯與外在內(nèi)容的分離拨黔,簡單的講就是讓PHP和HTML相分離蛔溃,讓程序員和美工同時進(jìn)行開發(fā),使的程序員改變程序的邏輯內(nèi)容時不會影響到美工的頁面設(shè)計,美工重新修改頁面時不會影響到程序的程序邏輯城榛。
官網(wǎng)地址
文件目錄
粗略的看一下幾個主要文件目錄揪利,根目錄下有個demo文件夾,里面放的就是使用smarty的一些例子狠持,那么還有一個libs文件夾疟位,里面放置的是smarty類文件,其中Smarty.class.php就是模板引擎的主文件喘垂,那么用的時候就是引入這個主文件進(jìn)行實例化然后操作甜刻,plugins這個目錄放置的是smarty的插件,其它目錄有興趣的下去了解一下正勒。
Smarty的引入與實例化
將Smarty的demo文件和主要類文件提出來
<?php
require_once '/smarty/Smarty.class.php';
$smarty = new Smarty();
Smarty的配置
1得院、五配置
$smarty->left_delimiter = '{';//左定界符
$smarty->right_delimiter = '}';//右定界符
$smarty->template_dir = 'tpl';//html模板的地址
$smarty->compile_dir = 'template_c';//模板編譯生成的文件
$smarty->cache_dir = 'cache';//緩存
$smarty->caching = true;//開啟緩存
$smarty->cache_lifetime = 120;//緩存時間
在模板里面出現(xiàn){}那么里面的任何語句都交給smarty去處理,在根目錄下創(chuàng)建三個目錄章贞。
2祥绞、常用兩方法
//模板變量賦值
$smarty->assign('變量名','變量值');
//展示模板
$smarty->display('test.html');
Smarty基本語法
//模板變量賦值
$arr = array('title'=>'網(wǎng)站標(biāo)題','content'=>'網(wǎng)站內(nèi)容');
$smarty->assign('arr',$arr);
//模板變量取值
{$arr.content} OR {$arr['content']}
Smarty變量調(diào)節(jié)器(相當(dāng)于函數(shù))
1、單詞首字母大寫
$smarty->assign('str','hello word');
{$str|capitalize}
2鸭限、字符串連接
$smarty->assign('str','hello word');
{$str|cat:' gsy'}
3蜕径、日期格式化
$smarty->assign('date',time());
{$date|date_format}
4、為未賦值或為空的變量指定默認(rèn)值
$smarty->assign('data');
{$data|default:'apple'|capitalize}
5败京、轉(zhuǎn)碼 escape 用于html轉(zhuǎn)碼兜喻,在沒有轉(zhuǎn)碼的變量上轉(zhuǎn)換單引號,十六進(jìn)制轉(zhuǎn)碼赡麦,十六進(jìn)制美化朴皆,或者javascript轉(zhuǎn)碼,默認(rèn)是html轉(zhuǎn)碼
$smarty->assign('url','https://www.smarty.net/docs/zh_CN/language.modifier.escape.tpl');
{$url|escape:'url'}
為什么要對url轉(zhuǎn)碼泛粹?因為在程序里面有很多符號會影響到PHP等等腳本語言的正常運轉(zhuǎn)遂铡。
6、轉(zhuǎn)換大小寫
$smarty->assign('str','Happy New Year');
{$str|lower}
{$str|upper}
7晶姊、將所有換行符替換成HTML標(biāo)簽
$smarty->assign('str',"Happy New Year\nHappy New Year\nHappy New Year");
{$str|nl2br}
條件判斷句式
1忧便、常用的條件修飾符
eq(==)
neq(!=)
gt(>)
lt(<)
2、基本句式
{if $name eq 'gsy'}
Hello gsy
{elseif $name eq 'wyx'}
Hello wyx
{else}
Hello
{/if}
使用修飾符時必須和變量用空格隔開
Smarty的foreach循環(huán)
$arr = array(0=>array('name'=>'霍建華','age'=>'20'),1=>array('name'=>'林心如','age'=>'18'));
$smarty->assign('arr',$arr);
{foreach item=person from=$arr}
<p>姓名:{$person.name}</p>
<p>年齡:{$person.age}</p>
{/foreach}
//從smarty3開始支持與PHP foreach一樣的語法
{foreach $arr as $person}
<p>姓名:{$person.name}</p>
<p>年齡:{$person.age}</p>
{/foreach}
Smarty的文件引用
//sitename屬性僅僅只能在引入文件中使用
{include file='header.html' sitename='網(wǎng)站主體'}
使用PHP內(nèi)置函數(shù)
$smarty->assign('date',time());
{'Y-m-d'|date:$date}
$smarty->assign('str','Hello word');
{'word'|str_replace:'Beijin':$str}