edevelops/native-tpl-heir

小巧的纯PHP原生模板继承库

0.0.1 2021-05-30 13:51 UTC

This package is auto-updated.

Last update: 2024-08-29 05:31:33 UTC


README

小巧的纯PHP原生模板继承库

Latest Stable Version Total Downloads Latest Unstable Version License

灵感来自 phpti

特性

  • 总共约35行代码
  • 无需了解任何除PHP之外的模板语言
  • 整个API仅包含3个全局函数!
  • 可重写的块不会被执行!
  • 没有使用 ob_* 缓冲

使用方法

不使用composer:直接复制/包含小巧的 源码

使用composer

$ composer require edevelops/native-tpl-heir

然后需要修改 NativeTplHeir 类以触发自动加载。例如

new NativeTplHeir();

API

  • slot(string $name, Closure $render = null) - 模板中块的输出点。 $name - 唯一的块名称。 $render - 可选的渲染回调。
  • block(string $name, Closure $render) - 定义在父模板的 slot 中输出的块。 $name - 唯一的块名称。 $render - 渲染回调。
  • super() - 调用被重写的父回调进行渲染。

继承

只需在文件末尾包含父模板 即可

示例

root.php

?>
<!DOCTYPE html>
<html>
  <head>
    <title><?php slot('title')?></title>
  </head>
  <body>
    <div id="root">
      <?php slot('body', function () { ?>

        <p>'body' :: root.php</p>

      <?php }) ?>
    </div>
  </body>
</html>

two-columns.php

block('title', function () { ?>
  Title :: two-columns.php
<?php });

block('body', function () { ?>
  <div id="two-columnts">
    <div id="main">
      <?php slot('main', function () { ?>

        <p>'main' :: two-columns.php</p>

      <?php }) ?>
    </div>
    <div id="side">
      <?php slot('side', function () { ?>

        <p>'side' :: two-columns.php</p>

      <?php }) ?>
    </div>
  </div>
  <div id="footer">
    <?php slot('footer', function () { ?>

      <p>'footer' :: two-columns.php</p>

    <?php }) ?>
  </div>

<?php });

include __DIR__.'/root.php';

index.php

block('title', function () { ?> 'title' :: index.php <?php });

block('side', function () { ?>

  <p>'side' :: index.php</p>

<?php }); 

block('main', function () { ?>

 <div id="main-index-override">
    <?php super() ?>
  </div>

<?php });

block('main', function () { ?>

  <div id="main-index"> 
    <?php super() ?>
  </div>

<?php });

include __DIR__.'/two-columns.php';

渲染结果(格式化以增强可读性)

<!DOCTYPE html>
<html>
  <head>
    <title> 'title' :: index.php </title>
  </head>
  <body>
    <div id="root">
      <div id="two-columnts">
        <div id="main">

          <div id="main-index-override">

            <div id="main-index"> 

              <p>'main' :: two-columns.php</p>

            </div>

          </div>

        </div>
        <div id="side">

          <p>'side' :: index.php</p>

        </div>
      </div>
      <div id="footer">

        <p>'footer' :: two-columns.php</p>

      </div>

    </div>
  </body>
</html>