Today 1.1 goals
- Grasp the actual use of Smarty template technology;
- Master the basic configuration Smarty template technology;
- Mastered the commonly used built-in functions smarty application;
- Master the use of a common template variables and the use of reserved variables;
- Learn Use smarty configuration file;
- Smarty grasp the built-in functions: use if branch, foreach loop and section
- Smarty introduced in class to master the way to achieve sub-class ease of use of
1.2 Variable
3 in smarty variables, simple variables, configuration variables, retain variables
1, ordinary variables
Our own common variable is the variable definition
Method One: Define in PHP
$smarty->assign('name','tom');
Method Two: You can define a template
语法:{assign var='变量名' value='值'}
例如:{assign var='sex' value='男'}
Simplify the wording:
{$sex='男'}
example:
php code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->assign('name','tom'); //给变量赋值
$smarty->display('1-demo.html');
HTML code
<body>
姓名:{$name} <br>
{assign var='age' value=20}
年龄:{$age}<br>
{$add='北京'}
地址:{$add}
</body>
operation result
2, variable retention
Smarty has a special reserved variables (built-in variables), like all the super-global variables in PHP, constants, time and other information
expression | description |
---|---|
{$smarty.get.name} | Gets the value of name get submitted |
{$smarty.post.name} | Gets the value of the name submitted by post |
{$smarty.request.name} | Gets the value of the name and post get submitted |
{$smarty.cookies.name} | Gets the value of the name of the cookie |
{$smarty.session.name} | Gets the value of the name of the session |
{$smarty.const.name} | Get constant name |
{$smarty.server.DOCUMENT_ROOT} | Gets the virtual directory server's address |
{$smarty.config.name} | Gets the value of the configuration file |
{$smarty.now} | Timestamp |
{$smarty.ldelim} | Gets Left definition |
{$smarty.rdelim} | Obtain the right to define |
example
PHP code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
define('name', '常量name');
setcookie('name','cookie的值');
$_SESSION['name']='session的值';
$smarty->display('1-demo.html');
HTML code
<body>
get提交:{$smarty.get.name}<br>
post提交:{$smarty.post.name}<br>
request提交:{$smarty.request.name}<br>
常量:{$smarty.const.name}<br>
cookie的值:{$smarty.cookies.name}<br>
session:{$smarty.session.name}<br>
时间戳:{$smarty.now}<br>
版本号:{$smarty.version}<br>
根目录:{$smarty.server.DOCUMENT_ROOT}<br>
左界定:{$smarty.ldelim}<br>
右界定:{$smarty.rdelim}
</body>
operation result
3, configuration variables
Fetch values from the configuration file, the configuration file is the default folderconfigs
1, create a configuration folder under Siteconfigs
2, configs
create a file in the directory smarty.conf
color='#FF0000';
size='15px';
3, PHP page
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->display('1-demo.html');
4, HTML page
{config_load file='smarty.conf'} <!--引入配置文件-->
<style>
body{
color:{#color#};
font-size: {$smarty.config.size}
}
</style>
summary:
1, to use the value of the configuration file, the configuration file must first be introduced, through the introduction of labels {config_load}
2, get the value in the configuration file, there are two methods
First: {# #} variable name
Second: {. $ Smarty.config} variable name
Learn a trick: the configuration file section
In the configuration file, '[]' represents a configuration file between
example:
Profiles
color=#FF0000
size=30px
[spring] # 配置文件中的段落
color=#009900;
size=20px;
[winter]
color=#000000;
size=5px;
note:
, Must be written in front of the global section 1
2, the configuration file [] represents a section
3, the configuration file comments is #
HTML page
{config_load file='smarty.conf' section='winter'} -- 通过section引入配置文件中的段落
<style>
body{
color:{#color#};
font-size: {$smarty.config.size}
}
</style>
Operators 1.3
smary the operator is the same as PHP. In addition, smarty also supports the following operators.
Operators | description |
---|---|
eq | equal equal |
neq | not equal is not equal |
gt | greater than greater than |
lt | less than less than |
lte | less than or equal or less |
gte | great than or equal or greater |
is even | Is even |
is odd | It is odd |
is not even | It is not even |
is not odd | Not an odd |
not | non- |
mod | Modulo modulo |
div by | Divisible |
is [not] div by | Can be a number divisible by, for example: {if $ smarty.get.age is div by 3} ... {/ if} |
is [not] even by | The result is an even number quotient |
is [not] odd by | Whether the result is an odd business |
1.4 judge
grammar:
{if 条件}
{elseif 条件}
{else}
{/if}
example:
php code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->display('1-demo.html');
html code
<body>
{if is_numeric($smarty.get.score)} {#判断是否是数字#}
{if $smarty.get.score gte 90}
A
{elseif $smarty.get.score gte 80}
B
{else}
C
{/if}
{else}
不是数字
{/if}
<hr>
{if $smarty.get.score is even}
是偶数
{elseif $smarty.get.score is odd}
是奇数
{/if}
</body>
operation result
Summary: The determination can be a function of the use PHP
1.5 Array
Smarty way to access an array of two
数组[下标]
数组.下标
PHP code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$stu=array('tom','berry'); //索引数组
$emp=array('name'=>'rose','sex'=>'女'); //关联数组
$goods=array(
array('name'=>'手机','price'=>22),
array('name'=>'钢笔','price'=>10)
);
$smarty->assign('stu',$stu);
$smarty->assign('emp',$emp);
$smarty->assign('goods',$goods);
$smarty->display('2-demo.html');
HTML code
<body>
学生:{$stu[0]}-{$stu.1} <br>
雇员:{$emp['name']}-{$emp.sex}<br>
商品:
<ul>
<li>{$goods[0]['name']}</li>
<li>{$goods[0].price}</li>
<li>{$goods.1['name']}</li>
<li>{$goods.1.price}</li>
</ul>
</body>
operation result
1.6 cycle
smarty supported circulates: {for}, {while}, {foreach}, {section}. For development, it is the most used {foreach} loop
1.6.1 for
grammar:
{for 初始值 to 结束值 [step 步长]}
{/for}
默认步长是1
example
<body>
{for $i=1 to 5}
{$i}:锄禾日当午<br>
{/for}
<hr>
{for $i=1 to 5 step 2}
{$i}:锄禾日当午<br>
{/for}
</body>
operation result
1.6.2 while
grammar
{while 条件}
{/while}
Examples (output 5):
<body>
{$i=1}
{while $i<=5}
{$i++}:锄禾日当午<br>
{/while}
</body>
1.6.3 foreach
Both traversing associative arrays can traverse the array index
grammar:
{foreach 数组 as $k=>$v}
{foreachelse}
没有数组输出
{/foreach}
foreach properties
@index:从0开始的索引
@iteration:从1开始的编号
@first:是否是第一个元素
@last:是否是最后一个元素
PHP code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->assign('stu',array('first'=>'tom','second'=>'berry','third'=>'ketty','forth'=>'rose'));
$smarty->display('3-demo.html');
html code
<table border='1' bordercolor='#000' width='780'>
<tr>
<th>是否是第一个元素</th>
<th>索引</th>
<th>编号</th>
<th>键</th>
<th>值</th>
<th>是否是最后一个元素</th>
</tr>
{foreach $stu as $k=>$v}
<tr>
<td>{$v@first}</td>
<td>{$v@index}</td>
<td>{$v@iteration}</td>
<td>{$k}</td>
<td>{$v}</td>
<td>{$v@last}</td>
</tr>
{foreachelse}
没有输出
{/foreach}
</table>
operation result
1.6.4 section
section does not support associative arrays, only to traverse the array index
grammar:
{section name=自定义名字 loop=数组}
{/section}
example:
php
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->assign('stu',array('tom','berry'));
$smarty->display('4-demo.html');
html code
<table border='1' bordercolor='#000' width='780'>
<tr>
<th>是否是第一个元素</th>
<th>索引</th>
<th>编号</th>
<th>值</th>
<th>是否是最后一个元素</th>
</tr>
{section name=s loop=$stu}
<tr>
<td>{$smarty.section.s.first}</td>
<td>{$smarty.section.s.index}</td>
<td>{$smarty.section.s.iteration}</td>
<td>{$stu[s]}</td>
<td>{$smarty.section.s.last}</td>
</tr>
{sectionelse}
没有输出
{/section}
</table>
1.7 Functions
There are two functions, custom functions and built-in functions
smarty built-in functions that PHP package keywords
1.8 Variable decorator
1.8.1 Variable decorator
Variable decorator is the essence of PHP function to convert the data
php code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->display('5-demo.html');
html code
<body>
转成大写:{'abc'|upper} <br>
转成小写:{'ABC'|lower} <br>
默认值:{$add|default:'地址不详'}<br>
去除标签:{'<b>你好吗</b>'|strip_tags}<br>
实体转换:{'<b>你好吗</b>'|escape}<br>
日期:{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}
多个管道连续使用:{'<b>boy</b>'|strip_tags|upper}<br>
</body>
operation result
note:
1, the keyword or function PHP packaged as tag function referred to, the package smarty PHP keywords to the keyword referred decorator. Are internal in nature, PHP PHP function or keyword.
2, |
known as the pipeline operator, the front of the back pass parameters after modification using
1.8.2 custom variables decorator
Variable decorator stored in the plugins directory
rule:
- The document naming rules: modifier modified variable name .php.
- The method of the file naming rules: smarty_modifier_ modified variable name (parameter ...)} {
example
1. Create modifier.cal.php page in the plugins directory
<?php
function smarty_modifier_cal($num1,$num2,$num3){
return $num1+$num2+$num3;
}
2, call the template
{10|cal:20:30}
10作为第一个参数传递
参数之间用冒号分隔
1.9 avoid Smarty parsing
smarty delimiters and css, js time in braces conflict, css, js the braces do not be parsed smarty
Method One: Replace the delimiter
Add a blank character left behind braces: Method Two
Method three: {literal} {/ literal}
smarty not interpret the contents of {literal} {/ literal} in
<style>
{literal}
body{color: #FF0000;}
{/literal}
</style>
1.10 Cache
Cache: page caching, spatial cache, data cache. smarty cache is in the page cache
smarty cache is page caching.
1.10 1 open the cache
$smarty->caching=true|1; //开启缓存
1.10.2 cache update
Method one: delete the cache, the system will regenerate a new cache file
Method Two: Update the template files, configuration files, the cache is automatically updated
Method three: After a cache of the life cycle, the default is 3600 seconds
Method four: update
PHP code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->caching=true; //开启缓存
if(date('H')>=9)
$smarty->force_cache=true; //强制更新缓存
$smarty->display('6-demo.html');
1.10.3 cache life cycle
$smarty->cache_lifetime=-1 | 0 | N
-1:永远不过期
0:立即过期
N:有效期是N秒,默认是3600秒
PHP code
$smarty->cache_lifetime=3; //缓存的生命周期
1.10.4 not cached locally
There are two approaches are not cached locally
1、变量不缓存 {$变量名 nocache}
2、整个块不缓存 {nocache} {/nocache}
Code
不缓存:{$smarty.now nocache} <br>
不缓存:{nocache}
{$smarty.now}<br>
{/nocache}
1.10.5 Paging Cache
By $ smarty-> display (template, identification id). By identifying tabs to cache id, set
PHP page
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->caching=1;
$smarty->display('7-demo.html',$_GET['pageno']);
html page
<body>
这是第{$smarty.get.pageno}页
</body>
operation result
1.10.6 cache set
Each combination will produce a cache
PHP code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
$smarty->caching=1;
$color=$_GET['color'];
$size=$_GET['size'];
$smarty->display('7-demo.html',"$color|$size");
HTML code
<body>
颜色:{$smarty.get.color}<br>
大小:{$smarty.get.size}
</body>
operation result
1.10.7 Clear Cache
$smarty->clearCache(模板,[识别id])
$smarty->clearAllCache(); //清除所有缓存
Code
<?php
require './Smarty/smarty.class.php';
$smarty=new Smarty();
//$smarty->clearCache('7-demo.html',1);
//$smarty->clearCache('7-demo.html','red|10');
//$smarty->clearCache('7-demo.html');
$smarty->clearAllCache(); //清除所有缓存
1.11 will be integrated into the project smarty
1, will be copied to the Lib directory smarty
2, the automatic loading type smarty
private static function initAutoLoad(){
spl_autoload_register(function($class_name){
//Smarty类存储不规则,所以将类名和地址做一个映射
$map=array(
'Smarty' => LIB_PATH.'Smarty'.DS.'Smarty.class.php'
);
...
elseif(isset($map[$class_name]))
$path=$map[$class_name];
else //控制器
$path=__URL__.$class_name.'.class.php';
if(file_exists($path) && is_file($path))
require $path;
});
}
3, creates hashed directory, and mixed-defined directory address
private static function initRoutes(){
...
define('__VIEW__',VIEW_PATH.$p.DS); //当前视图的目录地址
define('__VIEWC__', APP_PATH.'Viewc'.DS.$p.DS); //混编目录
}
4, since the front and back have to start template, so it should be instantiated on the basis of smarty controller
<?php
//基础控制器
namespace Core;
class Controller{
protected $smarty;
use \Traits\Jump;
public function __construct() {
$this->initSession();
$this->initSmarty();
}
//初始化session
private function initSession(){
new \Lib\Session();
}
//初始化Smarty
private function initSmarty(){
$this->smarty=new \Smarty();
$this->smarty->setTemplateDir(__VIEW__); //设置模板目录
$this->smarty->setCompileDir(__VIEWC__); //设置混编目录
}
}
5, the controller using smarty
class ProductsController extends BaseController{
//获取商品列表
public function listAction() {
//实例化模型
$model=new \Model\ProductsModel();
$list=$model->select();
//加载视图
//require __VIEW__.'products_list.html';
$this->smarty->assign('list',$list);
$this->smarty->display('products_list.html');
}
6, following changes in the template:
{foreach $list as $rows}
<tr>
<td>{$rows['proID']}</td>
<td>{$rows['proname']}</td>
<td>{$rows['proprice']}</td>
<td><a href="index.php?p=Admin&c=Products&a=edit&proid={$rows['proID']}">修改</a></td>
<td><a href="javascript:void(0)" onclick="if(confirm('确定要删除吗')){ location.href='index.php?p=Admin&c=Products&a=del&proid={$rows['proID']}'}">删除</a></td>
</tr>
{/foreach}
Exercise
46.【多选题】反馈
以下关于Smarty描述正确的是
A: Smarty是用PHP编写的优秀的模板引擎;
B: Smarty可以实现前端开发人员和后台程序员分离;
C: 采用Smarty编写的程序可以获得最大速度的提高;
D: 需要实时更新的内容和小项目不适合使用Smarty。