aesonus / message-templates
一个用于渲染部分内容作为消息的小型库
v1.0
2020-04-08 04:55 UTC
Requires (Dev)
- aesonus/test-lib: ^3.1
This package is auto-updated.
Last update: 2024-09-08 16:10:02 UTC
README
此库包含一些类,有助于将消息和其他模板渲染给用户。
用法
此包有许多用途,非常灵活。让我们看看。
模板来源
模板来源用于提供有关模板的渲染对象信息。
让我们看看一个例子
设置源数组
在这个例子中,我们将使用全局常量来从模板源中获取
const TEMPLATES = [ 'key1' => 'template string, %s', 'key2' => 'template string two, %s', ];
实现消息源接口
我们将为每个潜在键创建一个新类,该类将从抽象基类继承getTemplate方法。这是为了确保每个模板都将由一个独立的类表示,该类将返回来自同一源的正确模板。
abstract class ConstTemplateSource implements TemplateSourceInterface { public function getTemplate(): string { return TEMPLATES[$this->key]; } }
class Key1 extends ConstTemplateSource { protected $key = 'key1'; }
class Key2 extends ConstTemplateSource { protected $key = 'key2'; }
模板渲染
模板使用实现RenderTemplateInterface的类进行渲染。
添加到前面的例子,我们将使用包含的RenderVsprintfTemplate类
// Create the render object $template = new RenderVsprintfTemplate(); // Set the template source for the render object $template->setSource(new Key1); //Output the template with data echo $template->render(['purple']); //Outputs: template string, purple // Set another template source for the render object $template->setSource(new Key2); //Output the template with data echo $template->render(['red']); //Outputs: template string two, red
其他渲染实现
可以使用RenderTemplateInterface创建许多其他渲染实现。这可以允许使用像Twig这样的引擎来使用相同的来源渲染模板,甚至可以将变量设置在其他类的渲染模板中。