sitepoint/templating-engine

简单易用的PHP模板引擎

v0.1.0 2015-10-27 13:32 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:26:04 UTC


README

Latest Stable Version Build Status Code Coverage Scrutinizer Code Quality Code Climate Total Downloads License

这是一个简单易用的PHP模板引擎。设计用于可以被分支、修改、扩展和篡改。

示例用法

此模板引擎支持通过块进行继承。子模板可以声明可以被父模板覆盖、扩展和显示的块。

子模板可以在任何位置使用parent()方法声明单个父模板,这同时也提供了修改作用域内变量的机会。

所有模板必须遵循namespace::path/to/template格式。

<?php $this->parent('app::layout', ['title' => 'Blog Post: '.$title]); ?>

<?php $this->block('content', function ($params) { extract($params); ?>
    <article>
        <header>
            <h1><?=$this->escape($this->caps($title));?></h1>
        </header>
        <main>
            <?php foreach($paragraphs as $paragraph): ?>
                <p>
                    <?=$this->escape($paragraph);?>
                </p>
            <?php endforeach; ?>
        </main>
    </article>
<?php }); ?>
<html>
    <head>
        <title><?=$this->escape($title);?></title>
    </head>
    <body>
        <?=$this->block('content');?>
    </body>
</html>

命名空间和函数回调在模板引擎构造时注册。函数回调作为模板上下文中的方法可用,并且必须是callable

默认模板扩展名是phtml,但可以被覆盖。

use SitePoint\TemplatingEngine\TemplatingEngine;

$engine = new TemplatingEngine(
    ['app'  => '/path/to/templates/app'], // The namespaces to register
    ['caps' => 'strtoupper'],             // Function callbacks to register inside the template context
    'phtml'                               // The extension of the templates (defaults to phtml)
);

$params = [
    'title' => 'My Blog Post',
    'paragraphs' => [
        'My first paragraph.',
        'My second paragraph.',
    ],
];

echo $engine->render('app::post', $params);

模板上下文方法

以下方法默认在模板上下文中可用。

/**
 * Define a parent template.
 *
 * @param string $template The name of the parent template.
 * @param array  $params   Parameters to add to the parent template context
 *
 * @throws EngineException If a parent template has already been defined.
 */
public function parent($template, array $params = []);
/**
 * Insert a template.
 *
 * @param string $template The name of the template.
 * @param array  $params   Parameters to add to the template context
 */
public function insert($template, array $params = []);
/**
 * Render a block.
 *
 * @param string $name The name of the block.
 */
public function block($name, callable $callback = null);
/**
 * Escape a string for safe output as HTML.
 *
 * @param string $raw The unescaped string.
 *
 * @return string The escaped HTML output.
 */
public function escape($raw);

作者

变更日志

本项目维护一个变更日志文件

许可证

MIT许可证(MIT)。请参阅LICENSE以获取更多信息。