merge
merge
过滤器合并序列和映射
对于序列,新值会添加到现有值的末尾
1 2 3 4 5
{% set values = [1, 2] %}
{% set values = values|merge(['apple', 'orange']) %}
{# values now contains [1, 2, 'apple', 'orange'] #}
对于映射,合并过程发生在键上;如果键尚不存在,则会添加该键,但如果键已存在,则其值将被覆盖
1 2 3 4 5
{% set items = {'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown'} %}
{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}
{# items now contains {'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car'} #}
提示
如果您想确保在映射中定义某些值(通过给定的默认值),请反转调用中的两个元素
1 2 3 4 5
{% set items = {'apple': 'fruit', 'orange': 'fruit'} %}
{% set items = {'apple': 'unknown'}|merge(items) %}
{# items now contains {'apple': 'fruit', 'orange': 'fruit'} #}
注意
在内部,Twig 使用 PHP 的 array_merge 函数。它通过将 Traversable 对象转换为数组来支持它们。