美文网首页
Smarty初学知识整理

Smarty初学知识整理

作者: 小Q逛逛 | 来源:发表于2017-01-16 10:05 被阅读105次
  • web服务
web服务用的是SOAP(简单对象访问协议):是web服务的通信协议,用来定义返回消息的XML格式的规范
wsdl:web服务描述语言,包括一系列web服务的定义。
注意:PHP默认是不支持soap协议的,要开启soap协议

extension=php_soap.dll

<?php 
    $client = new SoapClient("http://webserver.com");
    $city=$client->getDomesticCity();
    echo "<pre>"
    var_dum($city);
?>

  • Smarty:用来将显示和内容相分离的框架

PHP代码 + HTML代码-->经过smarty将HTML中的定界符转换成PHP的定界符-->混编文件

//自定义smarty

<?php 
    $title = "静夜思";
    $content = "床前明月光,疑似地上霜,举头望明月,低头思故乡.";
    
    $str = file_get_contents('./demo.html');
    $str=str_replace('{','<?php echo $',$str);
    $str=str_replace('}',';?>',$str);
    file_put_contents('./demo.html.php',$str);
    
    require("./demo.html.php");
?>


优化smarty

上面例题中替换定界符的代码在每个PHP页面中都要出现,这样的代码不健壮,
解决:
将公共的代码封装到Smarty的compile()方法中

public function compile(){
    $str = file_get_contents('./demo.html');
    $str=str_replace('{','<?php echo $this->tpl_var["',$str);
    $str=str_replace('}','"];?>',$str);
    file_put_contents('./demo.html.php',$str);
    
    require("./demo.html.php");
}

封装后我们发现在类的内部不能输出类外面的变量。
解决:
定义一个私有属性用来保存变量,再定义一个共有的方法对私有的成员变量进行赋值。
<?php
    class Smarty{
        private $tpl_var=array();
        public function assign($k,$v){
            $this->tpl_var[$k] = $v;
        }
    }
?>

优化Smarty(二)
上面的缺点:每次执行页面,compile中替换字符串的代码都要执行,这样影响执行效率,
解决:
如果混编文件存在,并且混编文件的修改时间大于模板修改时间,则直接引入。否则重新生成。

public function compile(){
$compile_path=$tpl.'.php';
if(file_exists($compile_path) && filetime($compile_path) > filetime($tpl)){
    require $compile_path;
}else {
    echo 'create<br/>';
    $str = file_get_contents($tpl);
    $str=str_replace('{','<?php echo $this->tpl_var["',$str);
    $str=str_replace('}','"];?>',$str);
    file_put_contents($compile_path,$str);
    
    require($compile_path);
}
    
}

优化Smarty(三)
上面的缺点:所有的模板和混编文件都放在一起,不便于管理
解决:
新建一个模板文件夹(view,template),和编译文件夹(view_c,template_c),用来存放对应的文件



使用smarty

Smarty.class.php

templates:默认存放模板文件夹
templates_c:默认存放混编文件的文件夹
cache:存放缓存
configs:存放配置文件



注释
{*这是注释*}

  • smarty 的基础
普通变量
1、第一种声明方法:

require './Smarty/Smarty.class.php';
$smarty = new Smarty();
$smarty->assign("name","李白");
$smarty->display("demo.html");


2、第二种声明方法:
在模板文件中声明

{assign var="变量名" value="值"}

3.取值(不管声明的方法如何,取值方法一样)
{$name}
{$sex}

保留变量
在Smarty中有一个特殊的变量“smarty”,这个变量是保留变量,用来访问用户请求的信息,系统环境变量,常亮,类似于PHP中的超全局变量。
1.  获得get提交的值:例如:{$smarty.get.name}       $_GET
2.  获得post提交的值      {$smarty.post.变量名}    $_POST
3.  万能的获得值的方法      {$smarty.request.变量名}  $_REQUEST
4.  获取会话:               
在PHP中定义一个会话
$_SESSION["country"] = "China";
 
在模板中获取会话
{$smarty.session.country}
5、获取cookie
setCookie("school","peking university");
 
{$smarty.cookies.school}
6、显示常量
 define("city","shenzhen");
 
{$smarty.const.city}
7、取出服务器信息
{$smarty.server.REMOTE_ADDR}
8、取出当前时间
{$smarty.now}
9、其他的一些变量
{$smarty.version}
{$smarty.ldelim}
{$smarty.rdelim}

配置变量
1、在站点下新建configs文件夹,在文件夹中新建smarty.conf文件,代码如下:
 host=127.0.0.1
 username=root
 pwd=aaa
2、在模板文件中导入配置文件,并取值
 {config_load file="smarty.conf"}
 {#host#}<br>
 {#username#}<br>
 {#pwd#}
 
注意:
smarty将css的{解析了。
解决方法:
    1.更换定界符。
    2.在{后加空格
    3.使用{literal}{/literal}
    {literal}
        <style>
            div{...}
        </style>
    {/literal}


3、配置文件中的章节
[style1]  //定义章节
width="300px"
height="400px"
border="1 solid #F00"
backgroundcolor="#555";

调用章节中配置的变量
{config_load file="smarty.conf" section="style1"}

配置变量的注意:
(1)配置文件中的注释是“#”
(2)中括号表示节
(3)节定义的相当于局部变量
数组
smarty对数组的访问
1.  数组[下标]
2.  数组.下标
例如:
$smarty->assign("stu",array("tom","berry","ketty"));
$smarty->assign("emp",array("name"=>"libai","gender"=>"male"));

$smarty->assign('teacher',array(array("name"=>"libai","gender"=>"male"),array("name"=>"dufu","gender"=>"female")));

//访问
{$stu[0]}   {$stu.0}
{$emp.name}  {$emp["name"]}
{$teacher[0]["name"]}
{$teacher.0.["name"]}
{$teacher.0["name"]}
{$teacher[0].name}


foreach
如果不存在遍历的数组则执行{foreachelse}部分

{foreach $stu as $k=>$v}
{$k}:{$v}
{foreachelse}
{/foreach}

foreach内部关键字

语法 描述
值变量@iteration 从1开始的序号
值变量@index 从0开始的索引
值变量@first 判断是否是第一个元素
值变量@last 判断是否是最后一个元素
值变量@total 数组的长度
值变量@show 数组是否为空
<table>
    <tr>
        <th>是否是第一个元素</th>
        <th>编号</th>
        <th>索引</th>
        <th>键</th>
        <th>值</th>
        <th>是否是最后元素</th>
    </tr>
    
    {foreach $stu as $k->$v}
    {if $v@first}
    <tr class="first">
    {elseif $v@last}
    <tr class="last">
    {elseif $v@iteration%2==0}
    <tr class="even">
    {else}
    <tr>
    </if>
    
    <td>{$v@first}</td>
    <td>{$v@iteration}</td>
    <td>{$v@index}</td>
    <td>{$k}</td>
    <td>{$v}</td>
    <td>{$v@last}</td>
    
    {foreachelse}
    no such array;
    {/foreach}
</table>


判断
{if  条件}

{elseif  条件}

{else}

{/if}


section循环
只支持索引数组,不支持关联数组。
{section  name='自定义变量名'  loop='被遍历的数组'}
    {数组['自定义变量名']}
{/section}

section内置的关键字
{$smarty.section.自定义变量名.iteration}
{$smarty.section.自定义变量名.index}
{$smarty.section.自定义变量名.first}
{$smarty.section.自定义变量名.last}

{section name=s loop=$stu}
    {$stu[s]}-{$smarty.section.s.iteration}-{$smarty.section.s.index}
{/section}


for循环
{for $i=1 to 10}
    {$i}: Hello world<br>
{/for}

{for $i=1 to 10 step 2}
    {$i} : Hello world<br>
{/for}


while循环
{assign var='i' value=1}
{while $i<10}
    {$i++} : hello world<br>
{/while}


html_checkbox

1.
写法一
$smarty->assign('output',array('eating','play','sleep','swiming'));

<p>
    hobby:{html_checkboxes output=$output values=$value selected=$selected name='hobby' separator="<br>"}
</p>


2.写法二
$smarty->assign('options',array('a'=>'eating','b'=>'play','c'=>'sleep','d'=>'swiming'));

$smarty->assign('selected',array('a','c'));

<p>
    {html_checkboxes options=$options name='hobby' selected=$selected};
</p>


html_options:
<p>
{html_options options=$options name='hobby' selected=$selected multiple='multiple'};
</p>


html_radios:
{html_radios options=$options name='hobby' selected=$selected_radio};

  • 把已有的HTML和Smarty结合
1.在站点下新建public文件夹,在public文件夹中新建style,js,images文件夹,将素材copy到相对应的目录;

2.更改路径

<link href="/public/style/style.css" rel="stylesheet" type="text/css">

<script src="/public/js/jquery.js">

</script>
<script src="/public/js/my.js">

</script>

<style>
    p{background:url(../imges.third_03.jpg) over;}
</style>

注意:HTML页面中素材的路径从根开始匹配,CSS中按当前路径开始匹配。


3.PHP代码
require './Smarty/Smarty.class.php';

$smarty = new $smarty();

$ticket = array(
    array('世界',100,23,'电子/纸质','>90人');
    array('世界',120,21,'电子/纸质','>90人');
    array('世界',150,24,'电子/纸质','>90人');
    array('世界',1060,2,'电子/纸质','>90人');
);

$smarty->assign('ticket',$ticket);
$smarty->display('index.html');


4.html模板代码
{foreach $ticket as $v}
    <tr>
        <td height="25"> align="center"><input name="checkbox" value=""></td>
        <td align="center">{$v.0}</td>
        <td align="center">{$v.1}</td>
        <td align="center">{$v.2}</td>
        <td align="center">{$v.3}</td>
        <td align="center">{$v.4}</td>
    
    </tr>

</foreach}

  • Smarty布局
一.

1.在站点下新建文件夹layout,在文件夹中新建一个template.html模板

<body>
    <h2>Head</h2>
    {block name="main"}{/block}   //通过名字来替换
    <h3>Footer</h3>
</body>

2.在模板中的代码
{extends file="layout/template.html"}  //继承布局文件

{block name="main"}<strong>举头望明月,低头思故乡.</strong>{/block}   //替换


一个模板中可以由多个{block}
<body>
    <h2>Head</h2>
    {block name="main"}{/block}   //通过名字来替换
    <hr/>
    {block name="main2"}{/block}
    <h3>Footer</h3>
</body>



{extends file="layout/template.html"}  //继承布局文件

{block name="main"}<strong>举头望明月,低头思故乡.</strong>{/block}   //替换

{block name="main2"}
    过年我要回家!!!!
{/block}



二.

头,中间(左右),脚

可以把中间的部分全部替换,也可以把右边的部分替换,这样就可以实现一个布局文件用于多个模板。
1、新建模板:template.1.html
<body>
    <h2>Head</h2>
<block name="main">
    <div id="main">
        <div id="left">
            Link1<br>
            Link2<br>
            Link3<br>
        </div>
        {block name="right"}
            <div id="right"></div>
        {/block}
    </div>
</block>
<h3>Footer</h3> 
</body>


2.替换main

{extends file="layout/template.1.html"}
{block name="main"}
    床前明月光,疑是地上霜.举头望明月,低头思故乡.
{/block}

替换right
{extends file="layout/template.1.html"}
{block name="right"}
    床前明月光,疑是地上霜.举头望明月,低头思故乡.
{/block}

包含文件
{include file='文件的路径'}

如果公共部分多:用布局文件
如果公共部分少,用包含文件。
变量修饰器

在用“truncate”截取字符串的时候,默认情况下用utf8编码,一个中文在utf8下占用3个字节,所以容易出现乱码。
解决方法:

开启 extension=php_mbstring.dll;



缓存

require './Smarty/Smarty.class.php';
$smarty=new Smarty();
$smarty->caching=1;  //开启

$smarty->caching=1 |  true;开启smarty缓存,调用display()的时候,如有有缓存就从缓存中读取。
缓存文件的更新
1、删除对应的缓存
2、强制更新  $smarty->force_cache
3、更新模板,布局文件、包含文件。
4、设置缓存的生命周期。

$smarty->cache_lifetime=5;  //5秒

运算符
1、算术运算符
    一元运算符
        ++
        --
        -   一元减(负号)
    二元运算符
        +
        -
        *
        /
        %
    三元运算符
        条件?值1:值2

2、关系运算符
>
>=
<
<=
==
!=

3逻辑运算符

&&
||
!



相关文章

网友评论

      本文标题:Smarty初学知识整理

      本文链接:https://www.haomeiwen.com/subject/zngubttx.html