chrissileinus / template-php
一个从模板生成字符串的模板引擎。借助 ansiPHP 类,也可以使用 ANSI 代码为部分内容着色。
0.1.0
2022-03-17 07:22 UTC
Requires
- chrissileinus/ansi-php: ^0.1.0
This package is auto-updated.
Last update: 2024-09-29 06:03:13 UTC
README
一个从模板生成字符串的模板引擎。借助 ansiPHP 类,也可以使用 ANSI 代码为部分内容着色。
为什么
在寻找一个简单的模板引擎以在 bash 中生成一些输出时,我发现 nicmart/StringTemplate。但在需要具有着色功能的静态可调用方法时,我决定写一个类似的东西。
使用方法
占位符
默认情况下,占位符由 {
和 }
分隔,但您可以通过 Str::placeholders()
指定其他分隔符。
Chrissileinus\Template\Str::placeholders('a', 'b');
替换
如果未指定数组键,则将索引写入模板。
// @returns string: "This is my value: nic" Chrissileinus\Template\Str::replace("This is my value: {0}", ['nic']);
对于较长的模板,指定键是实用的。
// @returns string: "My name is Christian Backus" Chrissileinus\Template\Str::replace( "My name is {name} {surname}", [ 'name' => 'Christian', 'surname' => 'Backus' ] );
您还可以访问嵌套数组。
// @returns string: "My name is Christian and her name is Aline" Chrissileinus\Template\Str::replace( "My name is {my.name} and her name is {her.name}", [ 'my' => ['name' => 'Christian'], 'her' => ['name' => 'Aline'] ] );
您还可以提交多个数组。所有数组都通过 array_replace_recursive
按给定顺序合并。
// @returns string: "My name is Christian and her name is Aline" Chrissileinus\Template\Str::replace( "My name is {my.name} and her name is {her.name}", [ 'my' => ['name' => 'Christian'] ], [ 'her' => ['name' => 'Aline'] ] );
replaceFormat | replaceF
使用 sprintf,我们可以使用 转换规范 为占位符。
// @returns string: "My name is chris and my age is 041 [ 83.40]" Chrissileinus\Template\Str::replaceFormat( "My name is {user.name} and my age is {age%03d} [{weight%6.2f}]", [ 'user' => [ 'name' => "chris" ], 'age' => 41, 'weight' => 83.4, ] );
此外,我们还可以使用 ANSI 命令着色结果。对于在终端应用程序中的输出很有帮助。
只需一个额外的 &
和一个颜色和样式命令列表。它们也可以在输入数组中指定。
// @returns string: "My name is chris and my age is 041 [ 83.40]" Chrissileinus\Template\Str::replaceFormat( "My name is {user.name&user.color} and {my&user.color} age is {age&f_blue} {[{weight%6.2f}]&test.style}", [ 'user' => [ 'name' => "chris" ], 'age' => 41, 'weight' => 83.4, ], [ 'user' => [ 'color' => "f_yellow" ], 'test' => [ 'style' => "bold,f_magenta" ] ] );