PHP Smarty模板基础

<?php
//Smarty模板
//libs->plugins存放插件 libs->sysplugins存放系统自带插件
//Smarty.class.php核心类

class Smarty
{
    public $leftlimit="<{";//左分隔符
    public $rightlimit="}>";//右分隔符
    public $attr;//存放变量信息的数组
    
    //将一个变量存到数组里(注册变量)
    function assign($k,$v)
    {
        $this->attr[$k]=$v;
    }    
    
    //显示模板 原理
    function display($name)//括号里是要显示的模板的名称
    {
        //$name;//相当于index.html这样一个名称
        
        //造模板路径
        $filename=$mobanlujing.$name;
        
        //获取模板内容
        $str=file_get_contents($filename);
        
        /*str里面的内容
        <html>
        <head></head>
        <body>
        
        <div>{$aa}</div>
        </body>
        </html>
        */
        
        //用正则去匹配字符串中出现的{}里面的内容
        //将内容读取(读取到的是数组里面的key)拿key去数组attr里面取value值
        
        /*执行替换后str里面的内容
        <html>
        <head></head>
        <body>
        
        <div><?php echo $attr[key] ?></div>
        </body>
        </html>
        */
        
        //将str里面的内容保存在缓存文件里面
        file_put_contents($filename,$str);
        
        //将存储的文件加载到当前页面
        include(filename);
    }
}

 main.php

<?php
include("../init.inc.php");
$name="张三";
$age=12;
$attr=array("shi"=>"淄博","qu"=>"张店");

class Ren
{
    public $name="王五";
}
$r=new Ren();

$smarty->assign("name",$name);
$smarty->assign("age",$age);
$smarty->assign("dizhi",$attr);
$smarty->assign("ren",$r);

main.html

<h1>这是主页面</h1>
<div style="color:blue">登录者是:<{$name}></div>
<div>年龄是:<{$age}></div>
<div>地址是:<{$dizhi.qu}></div>
<div>好友:<{$ren->name}></div>

笔记

smarty的注释语法
1.<{*<div>你好</div> *}>
2.<!--<div>你好</div>-->

在smarty里不解析
{literal}
  中间内容会原样输出
{/literal}

配置文件
配置文件里的注释
1.;(在代码的前面写;可以注释一行)
2.#(在代码的前面写#可以注释一行)
配置文件对配置分块
[one]
bgcolor=green
配置文件的写入和读取
size=15px
[two]
bgcolor=blue
size=20px
读取
<{config_load file="style.conf" section="one"}>
<div bgcolor style="font-size:<{#size#}>px;bgcolor:<{#bgcolor#}>>第一个div</div>
<{config_load file="style.conf" section="two"}>
<div bgcolor style="font-size:<{#size#}>px;bgcolor:<{#bgcolor#}>>第二个div</div>

保留变量
<{smarty.now}>当前的时间戳
<{smarty.const}>存储的是定义的常量(是数组)不能直接读取,需要再.常量名,比如:<{smarty.const.root}>


smarty模板的内置函数
smarty模板里的if else
<{if $a gt 10}>
gt是大于
<{else}>
lt是小于
<{/if}>
smarty模板里的foreach
<{foreach $shuzu as $v}>
    <div><{$v}></div>
<{/foreach}>

<{foreach $shuzu as $k=>$v}>
    <div><{$v@index}>--<{$v@iteration}>--<{$v@first}>--<{$k}>--><{$v}></div>
<{/foreach}>
@index        下标从0开始
@iteration    下标从1开始
@first        第一行是true
@last         最后一行是true

 

posted @ 2016-07-14 11:28  Yao1101  阅读(182)  评论(0编辑  收藏  举报