Write a Smarty

Smarty V3.1.2

smarty's thoughts

Parsing tags into php output statements is the process from template files to php files.

The smarty debate

  • smarty compiling templates wastes time
  • Increased overhead in reassigning variables to object properties
  • Introduced the Smarty class

Simple implementation of Smarty


class miniSmarty {
    public $template_dir = ''; //模板文件所在的目录
    public $complete_dir = ''; //编译后文件所在目录

    // 定义一个数组,用来接收外部的变量
    public $_tpl_var = array();

    public function compile($template){
        $tempFile = $this->$template_dir . '/' . $template;
        // 读取模板文件内容
        $source = file_get_contents($tempFile);

        // 判断编译文件是否存在且模板文件修改时间小于编译后的文件的修改时间=》不用再次编译
        if(file_exists($compFile) && filemtime($tempFile)<filemtime($compFile)){
            return $compFile;
        }

        // 替换模板内容
        $source = str_replace('{$','<?php echo $this->_tpl_var[\'',$source);
        $source = str_replace('}','\'];?>',$source);

        // 再把编译后的文件保存成php文件
        $compFile = $this->$complete_dir . '/' . $template . '.php';
        file_put_contents($compFile,$source);

        return $compFile;
    }

    public fucntion assign($key,$value){
        $this->_tpl_var[$key] = $value;
    }

    public function display($template){
        $compileFile = $this->compile($template);
        include($compileFile);
    }
}

smarty's workflow

  1. Put the global variables that need to be displayed into the properties inside the object, in an array
  2. Compiling the template means parsing the {$ tag} into the corresponding php code
  3. Import the compiled php file

Steps to use Smarty

  1. Smarty is a class, first introduced and instantiated
  2. configure: template directory and build directory...
  3. assignassignment
  4. Call the display method and pass in the template file as a parameter
①引入smarty
require('../smarty3/smaty.class.php');
②实例化
$smarty = new Smarty();
③配置
$smarty->template_dir('../template');
$smarty->complete_dir('../complete');
④赋值
$smarty->assign('language','php');
$smarty->assign('frame','smarty3');
⑤编译模板并引入
$smarty->display('technology.html');

The template file technology.html to be compiled

<!DOCTYPE html>
<html>
<head>
    <title>{$frame}</title>
</head>
<body>
    {$language}
</body>
</html>

The compiled file technology.php

<!DOCTYPE html>
<html>
<head>
    <title><?php echo $this->_tpl_var['frame']; ?></title>
</head>
<body>
    <?php echo $this->_tpl_var['language']; ?>
</body>
</html>

smarty assign assigns an array

Get user information from database

require("./smarty.class.php");
$smarty = new Smarty();
$user = array("name"=>"元红娘","age"=>"7","weapon"=>"不属于当前世界的灵魂");

// ①
$smarty->assign("name",$user["name"]);
$smarty->assign("age",$user["age"]);
$smarty->assign("weapon",$user["weapon"]);

// ②
$le = array("name"=>"元灵儿","age"=>"5","weapon"=>"童心");
$smarty->assign("le",$le);

// ③
$lzy = array(0=>"梁智远",1=>"27","weapon"=>"马鞭");
$smarty->assign("$lzy",$lzy);

$smarty->display('news.html');

在news.html中,取值分别是:$name,$age,$weapon$le.name,$le.age,$le.weapon$lzy[0],$lzy[1],$lzy.weapon

smarty can assign values ​​such as strings, numbers, or an array of labels.
- When parsing the array in the template, you can use { $ tag.key } or { $ tag.index}
* when the key is a string, that is, associative array use { $ tag.key}
* when the key is a number, that is the index Arrays use { $ tag.key } or { $ tag.index}
- so using all { $ tag.key} works in all cases.

Smarty and js, css delimiter conflict solution

The default delimiter of smarty is { }, which may conflict with js and css in use, because the smarty engine treats the content between { } in js as a smarty statement.

Workaround:
1. Change the smarty delimiter, {%%}. (It's troublesome, and I'm used to using {})
2. Use {literal} {/literal} to include js and css, which tells the smarty engine that the intermediate code is not a smarty statement
3. Separate css or js{} with newlines

// ① 更改smarty定界符
$smarty->left-delimiter = '{%';
$smarty->right-delimiter = '%}';


// ② {literal} {/literal}
<style>
    {literal}
        table{background:pink;}
    {/literal}
</style>

// ③ 将css或js{}换行隔开
<style>
    table{
        background:pink;
    }
</style>

smarty assign in-depth discussion

According to smarty's source code, if the first parameter is an array, the
effect is to assign each value of the array to the label named on the corresponding key.

$lzy = array("name"=>"梁智远","age"=>"27");
$smarty->assign($lzy);

// 相当于
$smarty->assign("name","梁智远");
$smarty->assign("age","27");

Three sources of variables for smarty templates

The source corresponding to the smarty title variable, what else is there besides assign?

Answer:
The smarty tag variable comes from three parts.
1. It is the variable assigned by assign in php
2. The smarty system reserves the variable
3. The configuration variable read from the configuration file

// 三种变量来源之assign赋值
$smarty->assign("name","罗隐");
$smarty->assign("poem","我未成名君为家,可能俱是不如人");

// 三种变量来源之smarty系统保留变量,不用赋值,自动获取
在模板中直接取值`{$smarty.get.id}`

$smarty.开头的标签作为系统保留变量来解析
如:`{$smarty.get.id}`解析成<?php echo $_GET["id"];?>

$smarty.session,$smarty.cookies,$smarty.get,$smarty.post,$smarty.const.常量名

// 三种变量来源之从配置文件读取到的配置变量
《有些数据,比如网站底部的电话信息,不想入库,可以直接写到一个配置文件中,模板能读出配置文件的配置选项》

1. 配置文件一般以.conf做后缀
2. 配置文件的写法是
    *选项1 = 值1
    *选项2 = 值2
3.配置smarty的config_dir,并把配置文件放在该目录下。
在模板中载入配置文件{config_load file "site.conf" }
读取:{$smarty.config.site}
使用下面这种方式也可以读取
{#tel#}

//site.conf
site: 百度
tel: '13400134000'

Assignment and reference of smarty objects

  1. smarty can assign an array, can it assign an object?
  2. We always configure the Smarty template's template_dir and other options repeatedly, can it be simplified?
  3. Can I modify a variable that is referenced by a tag in a template?
  4. Can branch and loop output in php, can it be in template?
①引入smarty
require('../smarty3/smaty.class.php');
②实例化
$smarty = new Smarty();
③配置
$smarty->template_dir('../template');
$smarty->complete_dir('../complete');

class human {
    public $name = '张三';
    public $age = '25';

    public function say(){
        return 'hello world';
    }
}

$man = new human();

$smarty->assign('man',$man);

$smarty->display('object.html');

object.html

<!DOCTYPE html>
<html>
<head>
    <title>对象的引用是$标签->属性</title>
</head>
<body>
    <h2>{$man->name}</h2>
    <h2>{$man->age}</h2>

    <h1>调用对象的方法使用$标签->method();</h1>
    <p>{$man->name}说:{$man->say()}</p>

    所以,模板中的标签,应尽量只负责变量的 输出。
    就是负责显示数据的,不用负责太多的逻辑判断,函数调用等。
    所以,不推荐在模板中做逻辑判断及函数调用等。

</body>
</html>

Simplify template configuration with inheritance


// mySmarty.class.php

class MySmarty extend Smarty {

    // template_dir 和compile_dir 是父类的私有属性
    // 因此,无法复写,但是可以利用开放的接口来实现。
    public function __construct(){
        parent::__construct();

        $this->setTemplateDir('./template');
        $this->setCompileDir('./compile');
    }

}

  • Use Smarty again

require('../smarty3/smaty.class.php');
require('../mySmaty.class.php');

$smarty = new MySmarty();

class human {
    public $name = '张三';
    public $age = '25';

    public function say(){
        return 'hello world';
    }
}

$man = new human();
$smarty->assign('man',$man);
$smarty->display('object.html');
  • Refer to teacher Yan Shiba's smarty video tutorial, whose official website address is Boolean Education

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325725172&siteId=291194637