原生的PHP模板系统Plates教程

来源:admin  更新:2025/2/3 15:49  分类:网络技术  标签:php  源文件

Plates 是一个原生的 PHP模板系统 ,它快速、易于使用且易于扩展。它的灵感来自优秀的Twig模板引擎,并致力于将现代模板语言功能引入原生PHP模板。Plates专为那些更喜欢使用原生PHP模板而不是编译模板语言(如Twig或Smarty)的开发人员而设计。Plates is a native PHP template system that’s fast, easy to use and easy to extend. It’s inspired by the excellent Twig template engine and strives to bring modern template language functionality to native PHP templates. Plates is designed for developers who prefer to use native PHP templates over compiled template languages, such as Twig or Smart

特征:

  • 原生PHP模板,无需学习新语法
  • 板块是一个模板系统,而不是一种模板语言
  • Plates鼓励使用现有的PHP函数
  • 通过模板布局和继承提高代码重用率
  • 用于将模板分组到命名空间的模板文件夹
  • 跨模板的数据共享
  • 将数据预分配给特定模板
  • 内置逃生助手
  • 易于使用功能和扩展进行扩展
  • 框架无关,适用于任何项目
  • 解耦设计使模板易于测试
  • Composer,符合PSR-2标准

Plates使用一个名为“Engine”的中心对象,用于存储环境配置、功能和扩展。它有助于将模板与文件系统和其他依赖关系解耦。例如,如果要更改存储模板的文件夹,只需更改一个位置的路径即可。 Plates uses a central object called the Engine, which is used to store the environment configuration, functions and extensions. It helps decouple your templates from the file system and other dependencies. For example, if you want to change the folder where your templates are stored, you can do so by simply changing the path in one location.

用法

// Create new Plates engine
$templates = new League\Plates\Engine('/path/to/templates');

// Add any additional folders
$templates->addFolder('emails', '/path/to/emails');

// Load any additional extensions
$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));

// Create a new template
$template = $templates->make('emails::welcome');

Dependency Injection

Plates的设计便于在应用程序中传递,并易于注入控制器或其他应用程序对象。只需将“Engine”的实例传递给任何对象,然后使用“make()”方法创建新模板,或使用“render()”法立即渲染它。例如:

class Controller
{
    private $templates;

    public function __construct(League\Plates\Engine $templates)
    {
        $this->templates = $templates;
    }

    // Create a template object
    public function getIndex()
    {
        $template = $this->templates->make('home');

        return $template->render();
    }

    // Render a template directly
    public function getIndex()
    {
        return $this->templates->render('home');
    }
}

创建扩展再简单不过了。首先创建一个实现\League\Plates\Extension\ExtensionInterface的类。接下来,在register()方法中注册您的模板[functions]({{<relref“engine/functions.md”>}})。

扩展

use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;

class ChangeCase implements ExtensionInterface
{
    public function register(Engine $engine)
    {
        $engine->registerFunction('uppercase', [$this, 'uppercaseString']);
        $engine->registerFunction('lowercase', [$this, 'lowercaseString']);
    }

    public function uppercaseString($var)
    {
        return strtoupper($var);
    }

    public function lowercaseString($var)
    {
        return strtolower($var);
    }
}

要在模板中使用此扩展,只需调用新函数:

<p>Hello, <?=$this->e($this->uppercase($name))?></p>

它们也可以在批处理兼容的函数中使用:

<h1>Hello <?=$this->e($name, 'uppercase')</h1>

Single method extensions

您可以选择使用单个函数将整个扩展对象暴露给模板。这可以使您的模板更清晰,也可以减少与其他扩展冲突的机会。

use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;

class ChangeCase implements ExtensionInterface
{
    public function register(Engine $engine)
    {
        $engine->registerFunction('case', [$this, 'getObject']);
    }

    public function getObject()
    {
        return $this;
    }

    public function upper($var)
    {
        return strtoupper($var);
    }

    public function lower($var)
    {
        return strtolower($var);
    }
}

要在模板中使用此扩展,请先调用主函数,然后调用次函数:

<p>Hello, <?=$this->e($this->case()->upper($name))?></p>

Loading extensions

To enable an extension, load it into the [engine]({{< relref "engine/overview.md" >}}) object using the loadExtension() method.

$engine->loadExtension(new ChangeCase());

Accessing the engine and template

It may be desirable to access the engine or template objects from within your extension. Plates makes both of these objects available to you. The engine is automatically passed to the register() method, and the template is assigned as a parameter on each function call.


use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;

class MyExtension implements ExtensionInterface
{
    protected $engine;
    public $template; // must be public

    public function register(Engine $engine)
    {
        $this->engine = $engine;

        // Access template data:
        $data = $this->template->data();

        // Register functions
        // ...
    }
}
~~


Themes provide an alternative to template path resolution that allow for a holistic approach to template overrides and fallbacks.

## Themes

Given an engine configuration like:

```php
use League\Plates\{Engine, Template\Theme};

$plates = Engine::fromTheme(Theme::hierarchy([
    Theme::new('/templates/main', 'Main'), // parent
    Theme::new('/templates/user', 'User'), // child
    Theme::new('/templates/seasonal', 'Seasonal'), // child2
]));
```

And a file structure like:

```
templates/
  main/
    layout.php
    home.php
    header.php
  user/
    layout.php
    header.php
  seasonal/
    header.php
```

The following looks ups, *regardless of where they are called from*, would resolve to the following files:

```php
$templates->render('home'); // templates/main/home.php
$templates->render('layout'); // templates/user/layout.php
$templates->render('header'); // templates/seasonal/header.php
```

All paths are resolved from the last child to the first parent allowing a hierarchy of overrides.

## Themes Differences from Directory and Folders

This logic is used **instead of** the directories and folders feature since they are distinct in nature, and combining the logic isn't obvious on how the features should stack.

Creating an engine with one theme is functionally equivalent to using just a directory with no folders.

The fallback functionality is a bit different however since with folders, it's *opt in*, you need to prefix the template name with the folder name. With themes, all template names implicitly will be resolved and fallback according to the hierarchy setup.

## Themes Additional Customization

This functionality is powered by the `League\Plates\Template\ResolveTemplatePath` interface. If you'd prefer a more complex or specific path resolution, you can just implement your own and assign it to the engine instance with:

```php
$plates = Engine::withResolveTemplatePath(new MyCustomResolveTemplatePath());
```

The resolve template path should always resolve a string that represents a verified path on the filesystem or throw a TemplateNotFound exception

版权声明嗨网博客部分文章源自网络收集,不代表嗨网立场,如涉及侵权请联系嗨网删除。
其他若无特别说明则为嗨网原创文章、持续更新。未授权媒体、微信公众号不得使用嗨网内容。 个人自媒体可署名、保留原始链接的情况下转载
转载请注明 来源嗨网higrid.net,链接: https://higrid.net/posts/php-template-plates.html

本站为非盈利网站,作品由网友提供上传,如无意中有侵犯您的版权,请联系删除