Search code examples
twighigher-order-functionstwig-filter

How to map scalar twig filter to array


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.


Solution

  • Quick Answer (TL;DR)

    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
    • Custom filters or functions can also be used to simulate this

    Example

    • 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