marionnewlevant/twig-perversion

让Twig做它本不应做的事情

5.0.0 2024-04-29 16:34 UTC

This package is auto-updated.

Last update: 2024-09-24 16:30:21 UTC


README

悼词

由于Twig 3.12(Craft版本5.4)起,Twig Perversions的标签不再工作。以前,Twig会将它的宏编译成相当简单的函数,而Twig Perversion能够进行破解。现在它们正在使用生成器函数,旧的破解方法不再有效。

简介

让Twig做它本不应做的事情。Twig并不打算成为一个通用编程语言,有些事情根本不属于这个语言。这个插件仍然添加了一些这样的事情。

  • {% while %} 循环,{% break %}{% continue %},和 {% return %} 标签
  • ===!==<=> 操作符
  • is numericis stringis array 测试
  • array_splicestringfloatintbool 过滤器

要求

此插件需要Craft CMS 3.1.29或更高版本。

安装

  1. 从您的项目目录使用Composer安装: composer require marionnewlevant/twig-perversion
  2. 在Craft控制面板的设置 > 插件下安装插件

或者

  1. 通过 插件商店 安装

使用Twig Perversion

标签

  • {% while %} 循环

    {% set x = 0 %}
    {% while x < 5 %}
      {# do whatever... #}
      {% set x = x + 1 %}
    {% endwhile %}

    请注意,twig的 循环 变量(除了 revindexrevindex0lastlength)在while循环内部可用,以及 {% break %}{% continue %} 标签。

  • {% break %} 用于退出for循环或while循环

    {% for straw in haystack %}
      {% if straw == needle %}
        {% break %}
      {% endif %}
    {% endfor %}
    
    {% while true %}
      {# do whatever... #}
      {% if someCondition %}
        {% break %}
      {% endif %}
    {% endwhile %}
  • {% continue %} 用于继续到下一个迭代

    {% for straw in haystack %}
      {% if not isInteresting(straw) %}
        {% continue %}
      {% endif %}
      {# do whatever... #}
    {% endfor %}
  • {% return value %} 用于从宏返回值

    {% macro foo() %}
      {# ... calculate someValue ... #}
      {% return someValue %}
    {% endmacro %}
  • {% return %} 用于从宏返回空字符串

    {% macro foo() %}
      {# ... do stuff %}
      {% return %}
    {% endmacro %}

    带有 {% return %} 标签的宏将返回返回值(可以是复杂表达式)。宏生成的任何其他输出都将被丢弃。

操作符

  • ===!==

    使用php的 ===!== 操作符比较两个值的等价性。

  • <=>

    使用php的 <=> (spaceship) 操作符比较两个值。当第一个参数分别小于、等于或大于第二个参数时,返回 -101

测试

  • 数字

    测试给定值是否为数字(行为类似于PHP 7的 is_numeric)。(注意:从PHP 7开始,十六进制字符串不再被视为数字)

{{ 12 is numeric ? 'Yes' : 'No' }}
{# Yes #}

{{ '-1.3' is numeric ? 'Yes' : 'No' }}
{# Yes #}

{{ '0x539' is numeric ? 'Yes' : 'No'}}
{# No #}
  • 字符串

    测试给定值是否为字符串。

{{ '12' is string ? 'Yes' : 'No' }}
{# Yes #}

{{ 12 is string  ? 'Yes' : 'No' }}
{# No #}
  • 数组

    测试给定值是否为数组。

{ [] is array ? 'Yes' : 'No' }}
{# Yes #}

{{ '12' is array  ? 'Yes' : 'No' }}
{# No #}

过滤器

  • array_splice

    从数组中移除一部分并用其他内容替换。使用PHP的array_splice函数。注意,与PHP函数不同,此过滤器返回修改后的数组而不是提取的元素。原始数组保持不变。由于实现需要复制数组,这将比原始PHP函数效率低。array_splice过滤器接受一个offset,一个可选的length和一个可选的replacement

  • 字符串

    将变量转换为字符串。

  • 浮点数

    将变量转换为浮点数。

  • 整数

    将变量转换为整数。

  • 布尔值

    将变量转换为布尔值。

Marion Newlevant提供