如何将标量树枝过滤器映射到数组 [英] How to map scalar twig filter to array

查看:80
本文介绍了如何将标量树枝过滤器映射到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的浮点数组.我需要将其显示为逗号分隔的字符串.

I have a simple array of floats. And I need to show it as comma separated string.

{{ arr|join(', ') }}

由于准确性太低而无法解决问题.

is bad solution because of excessive insignificant accuracy.

{% for val in arr %}
    {{val|number_format(2)}},
{% endfor %}

不好,因为结尾有逗号.

is bad because of extra comma at the end.

我想做这样的事情:

{{ arr|map(number_format(3))|join(', ') }}

但是我没有找到过滤器map或类似的过滤器Twig. ?我不知道如何实现这种过滤器.

but I have not found filter map or similar filter it Twig. Аnd I don't know how to implement such filter.

推荐答案

快速解答(TL; DR)

  • 此问题与高阶函数有关
    • 地图是高阶函数
    • (请参见例如) https://en.wikipedia.org/wiki/Map_ (高级功能)
    • (请参见例如) https://en.wikipedia.org/wiki/Higher-order_function
    • Quick Answer (TL;DR)

      • This question relates to higher-order functions
        • Map is a higher-order function
        • (see eg) https://en.wikipedia.org/wiki/Map_(higher-order_function)
        • (see eg) https://en.wikipedia.org/wiki/Higher-order_function
          • Twig 2.x(Wed 2017-02-08的最新版本)
          • 场景::DeveloperGarricSugas希望将高阶函数应用于Twig变量
            • 高阶函数允许对任何Twig变量进行各种变换
            • Scenario: DeveloperGarricSugas wishes to apply higher-order function(s) to a Twig variable
              • Higher order functions allow any of various transformations on any Twig variable
              • DeveloperGarricSugas以顺序索引数组开头
              • BEFORE转换为AFTER(大写首字母)
              • DeveloperGarricSugas starts with a sequentially-indexed array
              • transform from BEFORE into AFTER (uppercase first letter)
              
              {%- set mylist = ['alpha','bravo','charlie','delta','echo']  -%}
              
              BEFORE: 
              ['alpha','bravo','charlie','delta','echo']
              
              AFTER: 
              ['Alpha','Bravo','Charlie','Delta','Echo']
              
              

              解决方案

              
              {%- set mylist = mylist|map(=> _|capitalize)  -%}    
              

              陷阱

              • Twig高阶函数的有限支持来自插件库
              • 上述解决方案不适用于本地Twig
              • Pitfalls

                • Twig higher-order functions limited support comes from addon-libraries
                • The above solution does not work with native Twig
                  • https://twigfiddle.com/rsl89m
                  • https://github.com/dpolac/twig-lambda

                  这篇关于如何将标量树枝过滤器映射到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆