Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Themes & Styling

Array slice and split in format

Started by Erdinc 9 years ago · 2 replies · 745 views
9 years ago

Hi,

I can't figure out split and join arrays... In twig file I want to split and join a set of array in a format like "xxx", "yyy", with quotes with comma. This array is ingredients of a recipe microdata. Every array comes with comma but in a single line with quotes. Like this: "xxx, yyy, zzz," which I want to make it [ "xxx", "yyy", "zzz" ]

Is there a way to make every array with quotes and end with comma?

{% set foo = page.header.ingredients|join(', ') %}
"recipeIngredient": "{{ foo }}",

9 years ago

|join() will stick array items together with some characters. However, it appears your already getting a string from your microdata, just comma separated.

I think you will need to |split() your string into array items, then loop over the items:

TWIG
{% set ingredients = "xxx, yyy, zzz" %}
{% for ingredient in ingredients|split(',') %}
"{{- ingredient|trim -}}", 
{% endfor %}

Something like that should output:

TXT
"xxx", "yyy", "zzz",
9 years ago

@rhuk:
|split(',')

Thanks @rhuk you rock :love_you_gesture::love_you_gesture:

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by Pedro M, 2 months ago
4 193 2 months ago
Themes & Styling · by Ian, 2 months ago
3 90 2 months ago
Themes & Styling · by Norbert, 2 years ago
11 449 3 months ago
Themes & Styling · by Lukáš Findeis, 3 months ago
0 44 3 months ago
Themes & Styling · by Sebadamus, 4 months ago
5 123 3 months ago