oofbar/craft-twig-toolbox 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

oofbar/craft-twig-toolbox

Composer 安装命令:

composer require oofbar/craft-twig-toolbox

包简介

Create your own Twig helpers.

README 文档

README

The simplest way to keep business logic out of your Twig templates.

All this plugin does is registers a Twig extension—everything else is up to you! With Twig Toolbox, you can finally start to clean up the mess that accumulates at the top of every template…

Usage

Twig Toolbox lets you inject custom filters, functions, globals, and tests into Craft’s template engine.

To get started, install the plugin from the Craft Plugin Store, or use Composer:

composer require oofbar/craft-twig-toolbox
php craft plugins/install twig-toolbox

Then, copy this into config/twig-toolbox.php:

<?php return [
    'filters' => [],
    'functions' => [],
    'globals' => [],
    'tests' => [],
];

💡 If you’re in the mood for a challenge, writing your own Twig extension is a great way to get familiar with custom module development.

Let’s look at some examples of how each language feature can be used.

Filters

→ Documentation on Twig Filters

The filters key should contain alphanumeric keys and functions or callables as values. Filters always have at least one argument!

Example

<?php return [
    'filters' => [
        'salePrice' => function(float $price): float {
            return $price * 0.9;
        },
    ],
];
<div class="product">
    <div class="sku">{{ product.sku }}</div>
    <span class="price price--default">{{ product.price | money }}</span>
    <span class="price price--members">{{ product.price | salePrice | money }}</span>
</div>

Functions

→ Documentation on Twig Functions

Each item in the functions array should have an alphanumeric key, and a function as its value. The function needs to declare expected arguments, and should explicitly return a value, if appropriate.

😄 You can use virtually any Craft API in a function!

Example:

<?php return [
    'functions' => [
        'getDeals' => function(): array {
            return Entry::find()
                ->section('products')
                ->onSale(true)
                ->all();
        },
        'log' => function(mixed $message): void {
            Craft::getLogger()->log($message);
        },
    ],
];
{# Use to fetch data for a loop... #}
{% for deal in getDeals() %}
    <div class="deal">
        <div class="title">{{ deal.title }}</div>
        <div class="expiry">{{ deal.saleEndDate | date('short') }}</div>
    </div>
{% else %}
    {# ...or just do something silently! #}
    {% do log('We didn’t show a user any deals!') %}

    <div class="empty">Sorry, there is nothing on sale right now.</div>
{% endfor %}

Globals

→ Documentation on Twig Globals

Globals are best used sparingly, and only for simple values. The new custom config in Craft 4 is a near equivalent!

⚠️ Be mindful of what you are assigning to a global! Calling some Craft or Plugin APIs can cause a race condition as the system initializes.

Example:

<?php return [
    'globals' => [
        'cutoffTime' => (new \DateTime)->modify('midnight'),
    ],
];
<h2>Prices are valid until {{ cutoffTime | date }}!</h2>

Tests

→ Documentation on Twig Tests

Tests are sort of like functions, but only available when using Twig’s is operator. They can do a lot to make your templates read more clearly—especially when the logic behind it is convoluted.

Examples

<?php

use craft\elements\User;

return [
    'tests' => [
        'expensive' => function(float $value): bool {
            return $value > 10.0;
        },
        'member' => function(User $user): bool {
            return $user->isInGroup('members');
        },
    ],
];
{% set image = product.image.one() %}

{% if product.price is expensive %}
    <img src="{{ image.url }}" class="shiny-effect">
{% else %}
    <img src="{{ image.url }}">
{% endif %}

Tips + Tricks

Callables

PHP has a special “type” for callable values. This includes the anonymous functions or “closures” we’ve used so far, in addition to a few other syntaxes that make it simple to add proxies to native PHP and Craft functions:

use craft\helpers\Number;

return [
    'filters' => [
        // Built-in PHP functions:
        'chunk' => 'array_chunk',
        // Craft helper proxy:
        'roman' => [Number::class, 'upperRoman'],
    ],
];

Handling Types

Some of the functions above could be made even more flexible by accepting the special mixed type, or a union type. For example, the expensive test could do some type checking and normalization like this...

<?php

use craft\elements\Entry;

return [
    'tests' => [
        'expensive' => function(float|Entry $value): bool {
            // Normalize an Entry into a scalar field value:
            if ($value instanceof Entry) {
                $value = $value->price;
            }

            return $value > 10.0;
        },
    ],
];

...then, the template can read a bit more fluidly:

{% if product is not expensive %}
    <button>Buy two!</button>
{% endif %}

Parameterization

filters and functions can take arguments to customize their behavior. If you find yourself adding a number of similar helpers, take a moment to consider how they could be consolidated and parameterized with one or more arguments.

HTML Helpers

Consider how Twig can help you generate HTML, rather than trying to build it up yourself!

<?php return [
    'functions' => [
        'bem' => function(string $base, array $flags): string {
            $classNames = [$base];

            // Create BEM-style class names, ignoring empty flags:
            foreach (array_filter($flags) as $flag) {
                $classNames[] = "{$base}--{$flag}";
            }

            return join(' ', array_unique($classNames));
        },
    ],
];
<div class="{{ bem('product', [
    product is expensive ? 'expensive' : null,
    currentUser is member ? 'member-pricing' : null,
]) }}">
    {{ product.title }}
</div>

Help + Support

If you’re having trouble getting started, create an issue on GitHub and we’ll do our best to help out! If you need support on a project-specific task (like finding the appropriate Craft APIs), we recommend posing it to the broader community.

oofbar/craft-twig-toolbox 适用场景与选型建议

oofbar/craft-twig-toolbox 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.78k 次下载、GitHub Stars 达 16, 最近一次更新时间为 2022 年 09 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 1.78k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 16
  • 点击次数: 6
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 16
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-09-19