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

Array slice and split in format

Started by Erdinc 9 years ago · 2 replies · 963 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 Sebadamus, 4 days ago
4 120 2 days ago
Themes & Styling · by martynfoster735, 7 days ago
1 176 6 days ago
Themes & Styling · by Justin Young, 3 weeks ago
1 232 3 weeks ago
Themes & Styling · by Slebeig, 1 month ago
4 364 1 month ago
Themes & Styling · by Pedro M, 3 months ago
4 730 3 months ago