SMARTY的知识

smarty的原理:

<?php
class Smarty
{
    $ldelimiter = "{";//左分隔符
    $rdelimiter = "}";//友分隔符

    $attr = array();//用来存贮变量的数组

    //向模板里面注册变量
    function assign($key,$value)
    {
        $this->attr[$key] = $value;
    }

    //显示模板的方法
    function display($url)
    {
        //1.获取静态模板的内容
        $str = file_get_contents($url);
        //2.根据正则匹配str里面出现的所有{}里面的内容
        //{$a} -> <?php echo $attr[$a] ?>

        //3.将替换好的页面保存临时文件
        touch(".test.php");
        file_put_contents();

        //4.将临时文件拿到当前页面显示
        include(".test.php");
    }
}

访问的是PHP文件,其中路径就按照访问的PHP文件来定。但是显示的是html。

test.php

test.php
<?php
include("../init.inc.php");
//注册变量
$smarty->assign("name","张三");
$smarty->assign("arr",array(1,2,3,4,5));
$smarty->assign("test","my name is zhangsan");
$smarty->assign("title",啊啊啊啊啊啊);
//显示模板
$smarty->display("test.html");

test.html

<html>
    <head></head>
    <body>
        <{$name}>
        <{$arr.one}>
        <{config_load file='test.conf'} section='one'>
        <div style="width:20px;height:20px;background-color:<{#color#}>"></div>
        <{$smarty.now|date_format:%Y-%m-%d %H:%M:%S}>
        <{$test|truncate:5}>//截取字符串
    

     <{date name ="riqi" value="2017-2-3" time=true}>
     <{color name="color"}>
     <{textarea name="txt" toolbar="full" color="red"}>
     <{/textarea}>//块函数要有首和尾
     
     <{cishu num=3}>
     <{font da=50}>
     电话卡会打架
     <{/font}>
     
</body> </html> $smarty.const.XXX 取常量 $smarty.config.color 和 #color#一样

test.conf

[one]
color=red
[two]
color=green

自定义变量调节器modifier.keyword.php

<?php
function smarty_modifier_keyword($str,$key)
{
    return str_replace($key,"<mark>{$key}</mark>",$str);
}

自定义函数function.cishu.php

//num参数代表输出次数
function smarty_function_cishu($args,$smarty)
{
    $num = $args["num"];
    
    $str = "";
    
    for($i=0;$i<$num;$i++)
    {
        $str = $str."<div style='width:100px;height:100px;background-color:green'></div>";
    }
    return $str;
}

自定义块函数block.font.php

<?php
function smarty_block_font($args,$content,$smarty,$a)
{
    if(!$a)//走头的时候没有内容,走尾的时候把内容改变
    {
        $da = $args["da"];
        
        return "<span style='font-size:{$da}px'>{$content}</span>";
    }
}

 

显示结果

 

 

 

 

 
posted @ 2017-04-26 16:34  v斌v  阅读(289)  评论(0编辑  收藏  举报