live627/fast-liquid-parser

v1.0.0 2023-03-22 13:58 UTC

This package is auto-updated.

Last update: 2024-09-22 18:32:28 UTC


README

Liquid是Ruby的Liquid模板引擎的PHP版本,由Tobias Lutke编写。尽管有许多其他PHP模板引擎,包括从Liquid中得到部分启发的Smarty,但Liquid有一些优点,使得移植值得

  • 易于阅读和人类友好语法,可用于任何类型的文档,而不仅仅是HTML,无需转义。
  • 快速且易于使用和维护。
  • 100%安全,不可能嵌入PHP代码。
  • 干净的OO设计,而不是其他模板引擎中常见的OO和过程式混合。
  • 独立的编译和渲染阶段,以提高性能。
  • 易于扩展,使用自己的"标签和过滤器":https://github.com/harrydeluxe/php-liquid/wiki/Liquid-for-programmers
  • 100%与Ruby模板引擎兼容的标记,使得模板可用于任一环境。
  • 单元测试:Liquid经过全面单元测试。该库稳定,适用于大型项目。

为什么选择Liquid?

为什么还需要另一个模板库?

Liquid是为了满足三个模板库要求而编写的:良好的性能、易于扩展和简单易用。

安装

您可以通过composer安装此库。

composer require liquid/liquid

示例模板

{% if products %}
	<ul id="products">
	{% for product in products %}
	  <li>
		<h2>{{ product.name }}</h2>
		Only {{ product.price | price }}

		{{ product.description | prettyprint | paragraph }}

		{{ 'it rocks!' | paragraph }}

	  </li>
	{% endfor %}
	</ul>
{% endif %}

如何使用Liquid

主类是Liquid::Template。与Liquid模板一起工作的两个独立阶段是:解析和渲染。以下是一个简单的示例

use Liquid\Template;

$template = new Template();
$template->parse("Hello, {{ name }}!");
echo $template->render(array('name' => 'Alex'));

// Will echo
// Hello, Alex!

要查找更多示例,请查看examples目录或原始Ruby实现存储库的wiki页面

高级使用

您可能希望添加缓存层(至少是请求范围内的),启用上下文感知的自动转义,并从磁盘加载具有完整文件名的包含文件。

use Liquid\Liquid;
use Liquid\Template;
use Liquid\Cache\Local;

Liquid::set('INCLUDE_SUFFIX', '');
Liquid::set('INCLUDE_PREFIX', '');
Liquid::set('INCLUDE_ALLOW_EXT', true);
Liquid::set('ESCAPE_BY_DEFAULT', true);

$template = new Template(__DIR__.'/protected/templates/');

$template->parse("Hello, {% include 'honorific.html' %}{{ plain-html | raw }} {{ comment-with-xss }}");
$template->setCache(new Local());

echo $template->render([
    'name' => 'Alex',
    'plain-html' => '<b>Your comment was:</b>',
    'comment-with-xss' => '<script>alert();</script>',
]);

输出结果

Hello, Mx. Alex
<b>Your comment was:</b> &lt;script&gt;alert();&lt;/script&gt;

请注意,自动转义不是Liquid的标准功能:请谨慎使用。

同样,以下片段将解析和渲染templates/home.liquid,同时将解析结果存储在类局部缓存中

\Liquid\Liquid::set('INCLUDE_PREFIX', '');

$template = new \Liquid\Template(__DIR__ . '/protected/templates');
$template->setCache(new \Liquid\Cache\Local());
echo $template->parseFile('home')->render();

如果您至少连续渲染相同的模板十二次,类局部缓存将使每次渲染的速度略有提升,具体取决于模板的复杂性。

您可能需要扩展Liquid\Template,以使用Liquid::set在同一个地方初始化您所做的一切。

自定义过滤器

添加过滤器从未如此简单。

$template = new Template();
$template->registerFilter('absolute_url', function ($arg) {
    return "https://www.example.com$arg";
});
$template->parse("{{ my_url | absolute_url }}");
echo $template->render(array(
    'my_url' => '/test'
));
// expect: https://www.example.com/test

要求

  • PHP 7.0+

某些早期版本可以在PHP 5.3/5.4/5.5/5.6中使用,但它们不再受支持。

问题

如果有bug,请在此GitHub上创建一个问题!

https://github.com/kalimatas/php-liquid/issues

分支说明

此分支基于Harald Hanek的php-liquid

它包含几个改进

  • 命名空间
  • 通过composer安装
  • 添加了新的标准过滤器
  • 添加了raw标签

任何帮助都将受到欢迎!