twig-filter

Twig - How to randomise items in the array and loop them?

南笙酒味 提交于 2019-12-07 08:57:10
问题 How can I randomise items in the array and loop them? {% for item in article.resources|shuffle|slice(1) %} ... {% endfor %} I get this error: Unknown "shuffle" filter in "partials/content.twig" at line 30. If I use random(): {% for item in random(article.resources|slice(1)) %} Nothing is returned. Any ideas? NOTES: I don't want to use PHP btw. 回答1: Twig Array Extension already has a shuffle() filter (based on PHP shuffle()) 回答2: Do something like that: $twig = new Twig_Environment($loader);

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

Twig - How to randomise items in the array and loop them?

给你一囗甜甜゛ 提交于 2019-12-05 14:23:13
How can I randomise items in the array and loop them? {% for item in article.resources|shuffle|slice(1) %} ... {% endfor %} I get this error: Unknown "shuffle" filter in "partials/content.twig" at line 30. If I use random() : {% for item in random(article.resources|slice(1)) %} Nothing is returned. Any ideas? NOTES: I don't want to use PHP btw. Twig Array Extension already has a shuffle() filter ( based on PHP shuffle() ) Do something like that: $twig = new Twig_Environment($loader); $function = new Twig_SimpleFunction('shuffle', function ($array) { shuffle($array); return $array; }); $twig-