牛骨文教育服务平台(让学习变的简单)

自定义扩展

如果系统自带的解析规则不能满足需求, 可以使用 Angular::extend()方法进行扩展, 此方法有两个参数, 详细请看下面实例.

入口文件: /test/index.php

<?php
use thinkangularAngular;
require "../src/Angular.php";

// 自定义扩展, 打印变量的值
Angular::extend("dump", function ($content, $param, $angular) {
    $old = $param["html"];
    $new = "<pre>";
    unset($param[0], $param[1], $param[2], $param[3], $param[4], $param[5]);
    $new .= "<?php var_dump(" . $param["value"] . ");  ?>";
    $new .= "<pre>";
    return str_replace($old, $new, $content);
});

// 自定义扩展, 变量+1
Angular::extend("inc", function ($content, $param, $angular) {
    $old = $param["html"];
    $new = "<?php " . $param["value"] . "++; ?>";
    $new .= Angular::removeExp($old, $param["exp"]);
    return str_replace($old, $new, $content);
});

// 自定义扩展, 变量-1
Angular::extend("dec", function ($content, $param, $angular) {
    $old = $param["html"];
    $new = "<?php " . $param["value"] . "--; ?>";
    $new .= Angular::removeExp($old, $param["exp"]);
    return str_replace($old, $new, $content);
});

/ 配置
$config = [
    "debug"            => true, // 是否开启调试, 开启调试会实时生成缓存
    "tpl_path"         => "./view/", // 模板根目录
    "tpl_suffix"       => ".html", // 模板后缀
    "tpl_cache_path"   => "./cache/", // 模板缓存目录
    "tpl_cache_suffix" => ".php", // 模板缓存后缀
    "directive_prefix" => "php-", // 指令前缀
    "directive_max"    => 10000, // 指令的最大解析次数
];

// 实例化
$view = new Angular($config);

// 输出解析结果
$view->display("index");

模板文件: /text/view/index.html

<!DOCTYPE html>
<html>
    <head>
        <title>diy test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        <div php-dump="$navs"></div>
        <div php-init="$i = 0" php-inc="$i" php-inc="$i">{$i}</div>
        <div php-dec="$i">{$i}</div>
    </body>
</html>

解析后

<!DOCTYPE html>
<html>
    <head>
        <title>diy test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        <pre><?php var_dump($navs);  ?><pre>
        <?php $i = 0;  $i++;  $i++; ?>
        <div><?php echo $i; ?></div>
        <?php $i--; ?>
        <div><?php echo $i; ?></div>
    </body>
</html>