How to map scalar twig filter to array

北城以北 提交于 2019-12-07 03:25:24

问题


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.

I would like to do something like this:

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

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


回答1:


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

Detailed Answer

Context

  • Twig 2.x (latest version as of Wed 2017-02-08)

Problem

  • 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
  • Twig support for higher-order functions is limited
  • Nevertheless, there exist addon libraries for this
    • (see eg) https://github.com/dpolac/twig-lambda
  • Custom filters or functions can also be used to simulate this

Example01

  • 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']

Solution

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

Pitfalls

  • Twig higher-order functions limited support comes from addon-libraries
  • The above solution does not work with native Twig

See also

  • https://twigfiddle.com/rsl89m
  • https://github.com/dpolac/twig-lambda



回答2:


Why not use the loop variable?

{% for val in arr %}
    {{val|number_format(2)}}
    {% if not loop.last %}, {% endif %}
{% endfor %}



回答3:


Quick Answer (TL;DR)

  • alternate approach is to use Twig loops (workaround)

Workaround

{%- set aaold = [1.234,234.56,11.222,22.333]  -%}
{%- set aanew = []  -%}
{% for item in aaold -%}
  {{ aanew|merge(item|number_format(3)) }}
{% endfor %}
{{ aanew | join(', ') }}

Pitfalls

  • requires use of array|merge
    • alternative to array|merge ... loop.first or loop.last as specified here
  • requires addition of loop control structure that means extra code bloat


来源:https://stackoverflow.com/questions/40223924/how-to-map-scalar-twig-filter-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!