nafisc / spackle
PHP 的模板系统
v1.1
2019-05-18 04:20 UTC
This package is auto-updated.
Last update: 2024-09-04 15:50:16 UTC
README
PHP 的简单模板引擎
Spackle 允许您向任何文件添加代码块和替换。
创建模板
替换
替换表示法:
{{...}}
<body>
Hello, my name is {{name}}.
</body>
替换将根据其解析器的配置进行替换。
代码块
代码块表示法:
{{> ... <}}
<body>
{{>
echo "Hello, Word!";
<}}
</body>
代码块总是最后解析,这样您可以在代码块中使用替换和其他插件。
<ul>
{{>
foreach ({{likes}} as $likeable) {
echo '<li>';
echo $likeable;
echo '</li>';
}
<}}
</ul>
插件
插件表示法:
{{key ... <}}
您可以创建自己的插件来解析自定义模板键。
请参见 CodeBlockParser.php 中的插件示例。
class MyPlugin extends \Spackle\Plugin { // The key used to notate the beginning of this element. public $key = 'url'; // Parse each element found matching this plugin. // {{url some/data <}} woud come out to https:///some/data public function parse($data) { return 'https:///'.$data; } } . . . // Add on a global scope \Spackle\Plugin::add(new MyPlugin()); // Add to a specific parser $parser->addPlugin(new MyPlugin());
解析模板
创建模板后,您可以在 PHP 中解析它。要解析模板,您需要创建 \Spackle\TemplateParser 的实例。在以下示例中,我们将使用 \Spackle\FileParser 类。它是 TemplateParser 的子类,唯一的不同之处在于它加载文件内容而不是使用字符串。
对于此示例,我们将使用存储在 ./test.spackle 中的以下 Spackle 模板。
<h4>Welcome to Spackle!</h4> Spackle was created by <a href="{{github_url}}" target="_blank">{{name}}</a>.<br /> Some things that {{name}} likes are:<br /> <ul> {{> foreach ({{likes}} as $likeable) { echo '<li>'; echo $likeable; echo '</li>'; } <}} </ul> <b>Bound: {{> echo $this->bound; <}}
现在,为了解析它,我们需要告诉它使用哪些值。
<?php include_once __DIR__.'/vendor/autoload.php'; use \Spackle\FileParser; // The FileParser extends the TemplateParser // and instead of cunstructing with a string // is uses a file path. $parser = new FileParser( // Template File Path __DIR__.'/test.spackle', // Optional Substitutions (add more with $parser->setSubstitution($key, $val)) [ 'github_url' => 'https://github.com/nathan-fiscaletti/', ] ); // You can set substitutions easily using the setSubstitution // member function of a TemplateParser. $parser->setSubstitution('name', 'Nathan Fiscaletti'); // You can also bind the Parser to a specific object. // Anytime you reference `$this` in your code blocks // within the template, this bound object will be // referenced. $bindTest = (object)[ 'bound' => 'Yes, Bound.' ]; $parser->bindTo($bindTest); // You can use functions for substitutions. // When the return value is an integer or // a string, it will be directly substituted. // Otherwise, the value will be used. $parser->setSubstitution('likes', function() { return ['Coding', 'PHP', 'Trial by Combat']; }); // The ->parse() function will parse the template // and return the parsed value. echo $parser->parse();
这应该输出类似以下内容
Welcome to Spackle!
Spackle was created by Nathan Fiscaletti.
Some things that Nathan Fiscaletti likes are:
* Coding
* PHP
* Trial by Combat
Bound: Yes, Bound.
(您可以在 ./example/ 中找到此示例)
为什么就到这里呢?
由于它是一个正则表达式匹配器,因此您可以使用 Spackle 处理任何您想要的文件类型。
例如,JavaScript
console.log("Hello, {{name}}!");