rybakit / twig-deferred-extension
为 Twig 提供的一个扩展,允许延迟块渲染。
v3.0.5
2024-04-04 09:38 UTC
Requires
- twig/twig: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpunit/phpunit: ^6.1|^7.0|^8.0|^9.0
README
为 Twig 提供的一个扩展,允许延迟块渲染。
安装
composer require rybakit/twig-deferred-extension
注意,此扩展需要 Twig 3 或更高版本。如果您需要支持旧版本的 Twig,请参阅遗留仓库。
初始化
use Twig\DeferredExtension\DeferredExtension; use Twig\Environment; ... $twig = new Environment($loader); $twig->addExtension(new DeferredExtension());
简单示例
{% block foo deferred %} {{ bar }} {% endblock %} {% set bar = 'bar' %}
foo
块将输出 "bar"。
高级示例
仅作为示例,首先创建一个 全局 Twig 变量
use Twig\Environment; ... $twig = new Environment($loader); $twig->addGlobal('assets', new \ArrayObject());
然后构建以下模板集
{# layout.html.twig #} <!DOCTYPE html> <html> <head> ... </head> <body> {% block content '' %} {{ assets.append('/js/layout-header.js') }} {% block javascripts deferred %} {% for asset in assets %} <script src="{{ asset }}"></script> {% endfor %} {% endblock %} {{ assets.append('/js/layout-footer.js') }} </body> </html> {# page.html.twig #} {% extends "layout.html.twig" %} {% block content %} {{ assets.append('/js/page-header.js') }} {% if foo is defined %} {{ include("subpage1.html.twig") }} {% else %} {{ include("subpage2.html.twig") }} {% endif %} {{ assets.append('/js/page-footer.js') }} {% endblock %} {# subpage1.html.twig #} {{ assets.append('/js/subpage1.js') }} {# subpage2.html.twig #} {{ assets.append('/js/subpage2.js') }}
生成的 HTML 将如下所示
<!DOCTYPE html> <html> <head> ... </head> <body> <script src="/js/layout-header.js"></script> <script src="/js/page-header.js"></script> <script src="/js/subpage2.js"></script> <script src="/js/page-footer.js"></script> <script src="/js/layout-footer.js"></script> </body> </html>
块覆盖
{# index.twig #} {% extends "base.twig" %} {% block foo %}foo is not deferred anymore{% endblock %} {% block bar deferred %}bar is deferred now{% endblock %} {# base.twig #} {% block foo deferred %}foo is deferred{% endblock %} {% block bar %}bar is not deferred{% endblock %}
许可
该库在 MIT 许可下发布。有关详细信息,请参阅捆绑的 LICENSE 文件。