定制 mediagone/twig-powerpack 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mediagone/twig-powerpack

Composer 安装命令:

composer require mediagone/twig-powerpack

包简介

Provides code-quality helpers to your Twig templates.

README 文档

README

⚠️ This project is in experimental phase.

Latest Version on Packagist Total Downloads Software License

This package provides code-quality features to your Twig templates:

  1. Type-safety checks for template context variables.
  2. Register global data/resources from any template.
  3. Instantiate classes in templates.

Along with new functionalities:

  • |json_decode filter

Installation

This package requires PHP 7.4+ and Twig 2+.

Add it as Composer dependency:

$ composer require mediagone/twig-powerpack

If you're using Symfony, enable the extension in services.yaml:

services:
    
    Mediagone\Twig\PowerPack\TwigPowerPackExtension:
        tags: [twig.extension]

Introduction

Twig templating engine is seriously lacking types....

Features

1) Context Variables type-checking

Templates usually require specific external data, but there is no native way to check the type of supplied variables. The expect tag allows you to declare required variables in your Twig files, making them also self-documenting. If the data is invalid, an exception will be thrown.

Primitive types

Supported scalar types are: bool, float, int and string.

{% extends 'layout.twig' %}

{% expect 'string' as TITLE %}
{% expect 'bool' as ENABLED %}
{% expect 'float' as AMOUNT %}
{% expect 'int' as COUNT %}

Note: TITLE, ENABLED, AMOUNT and COUNT represent the names of required variables.

Objects

Because they don't guarantee any data structure, anonymous objects (stdClass) are not supported. However, usage of named classes is strongly encouraged to expose data in your templates. Therefore, a Fully Qualified Class Name (FQCN) can also be supplied:

{% expect 'App\\UI\\ViewModels\\Foo' as FOO %}

{{ FOO.bar }}

Nullable

Sometimes, you may want to ensure that a variable is defined while making it optional by using the nullable keyword:

{% expect nullable 'App\\UI\\ViewModels\\Foo' as FOO %}

{% if FOO != null %}
...
{% endif %}

Arrays

You can also check if a variable is an array of a given type by using the array of keywords:

{% expect array of 'App\\UI\\ViewModels\\Foo' as ARRAY %}

{% for foo in ARRAY %}
...
{% endfor %}

Arrays can also be nullable:

{% expect nullable array of 'App\\UI\\ViewModels\\Foo' as ARRAY %}

{% if ARRAY != null %}
...
{% endif %}

Or contain nullable elements:

{% expect array of nullable 'App\\UI\\ViewModels\\Foo' as ARRAY %}

{% for foo in ARRAY %}
    {% if foo != null %}
    ...
    {% endif %}
{% endfor %}

And even nullable array of nullable elements!

{% expect nullable array of nullable 'App\\UI\\ViewModels\\Foo' as ARRAY %}

Note: Checking array's items type might induce a slight overhead, but unless you have thousands of elements it should be negligible.

2) Register global data from any template

You may occasionally declare specific data in your templates, used in the global scope. For example if your templates dynamically add CSS classes to HTML body, or if they require optional CSS or JavaScript resources you only want to include on demand.

String Data

Short string data can be registered from anywhere in your templates using the {% register <data> in <registry> %} tag:

// Page.twig

{% extends 'Layout.twig' %}

{% register 'has-menu' in 'bodyClasses' %}
{% register 'responsive' in 'bodyClasses' %}

{% register '/css/few-styles.css' in 'styles' %}
{% register '/css/some-styles.css' in 'styles' %}

{% register '/js/custom-scripts.js' in 'scripts' %}

...

And retrieved elsewhere through the registry() function:

// Layout.twig

<html>
    <head>
        ...
        
        {% for css in registry('styles') %}
        <link rel="stylesheet" href="{{ css }}" />
        {% endfor %}
        <!-- <link rel="stylesheet" href="/css/few-styles.css" /> -->
        <!-- <link rel="stylesheet" href="/css/some-styles.css" /> -->
    </head>
    <body class="{{ registry('bodyClasses')|join(' ') }}">
    <!-- <body class="has-menu responsive"> -->
        ...
        
        {% for js in registry('scripts') %}
        <script src="{{ js }}"></script>
        {% endfor %}
        <!-- <script src="/js/custom-scripts.js"></script> -->
    </body>
</html>

Optional registry clause

For convenience, the registry name can be automatically inferred from the data when it represents a path with an extension, making usage of in <registry> optional. The following lines are equivalent:

{% register '/styles.css' in 'css' %}
{% register '/styles.css' %}

Body Data

Because you may need longer or dynamically generated data, the tag also supports a block syntax to allow a content body to be provided. In this case you cannot define data in the opening tag and the registry clause is mandatory: {% register in <registry> %} <body data> {% endregister %}

For example if you want to declare inline scripts from a template:

// Page.twig
{% extends 'Layout.twig' %}

{% set name = 'world' %}

{% register in 'inlineJs' %}
    alert('Hello {{ name }}');
{% endregister %}

And include it at the end of the html page:

// Layout.twig

<html>
    <body>
        ...
    
        <script>
        {% for js in registry('inlineJs') %}
            {{ js|raw }}
        {% endfor %}
        <!-- alert('Hello world'); -->
        </script>
    </body>
</html>

Unicity

Data can be declared as unique, so if multiple templates register the same value, it will be included only once. It's required most of the time, just add the once keyword to the tag:

{% register once '/styles.css' %} 

// Subsequent identical statements will be ignored
{% register once '/styles.css' %}

It also works with body data:

{% register once '/styles.css' %}
{% register once in 'css' %}/styles.css{% register %}  // ignored

However, unicity is only enforced within the same registry, so both following statements will be taken into account:

{% register once '/styles.css' in 'css' %}
{% register once '/styles.css' in 'styles' %}

Priority

As you cannot always predict in which order data will be registered, you'll sometime need to ensure a data comes first, for example in the case of a script library required by others. Then, add the priority keyword at the end of your tag followed by a priority number (lower values come first*).

Tags without priority always come after prioritized ones.

Note: the order of data with the same priority (or undefined) is not guaranteed.

{% register '/last.js' %}
{% register '/second.js' priority 2 %}
{% register '/first.js' priority 1 %}

<!-- <script src="/first.js"></script> -->
<!-- <script src="/second.js"></script> -->
<!-- <script src="/last.js"></script> -->

3) Instantiate classes in templates

Although it's better to do it in the controller when possible, you may need to create class instances directly in a template. The new(string $fqcn, ...$args) function allows you to call the constructor of a given class:

{% include('Partials/Menu.twig') with {Menu: new('App\\UI\\Partials\\Menu',
    'Main menu',
    [
        {Label: 'Item 1', Href: '/url/to/item1'},
        {Label: 'Item 2', Href: '/url/to/item2'},
    ],
)} %}

Given the following View Model class:

namespace App\UI\Partials;

final class Menu
{
    private string $name;
    private array $items;
    
    public function __construct(string $name, array $items)
    {
        $this->name = $name;
        $this->items = array_map(static fn($item) => new MenuItem($item), $items);
    }
}

License

Twig PowerPack is licensed under MIT license. See LICENSE file.

mediagone/twig-powerpack 适用场景与选型建议

mediagone/twig-powerpack 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.43k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2021 年 01 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「twig」 「extension」 「quality」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mediagone/twig-powerpack 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mediagone/twig-powerpack 我们能提供哪些服务?
定制开发 / 二次开发

基于 mediagone/twig-powerpack 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.43k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 7
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-01-02