Mark Notton Mark Notton - 2 months ago 15
Twig Question

Convert Twig array to a PHP array

Using file_get_contents I'm able to get the contents of a twig file which contains just one multidimensional array:

Twig:

{% set settings = {
theme : '#91141b',
transforms : {
thumb : { mode:'crop', width:300, height:300, quality:80, position:'center-center'},
small : { mode:'fit', width:100, height:100, quality:70, position:'center-center'},
header : { mode:'fit', height:800, quality:80, position:'center-center'},
mobile : { mode:'crop', width:640, height:1136, quality:60, position:'center-center'}
},
globals : {
telephone : '123456678',
address : '42 Wallaby Way, Sydney'
},
social : {
facebook : 'http://www.facebook.com',
twitter : 'http://www.twitter.com',
linkedin : 'http://www.linkedin.com',
youtube : 'http://www.youtube.com'
}
} %}


In PHP, I now have this string to play with:

{% set settings = { theme : '#91141b', transforms : { thumb : { mode:'crop', width:300, height:300, quality:80, position:'center-center'}, small : { mode:'fit', width:100, height:100, quality:70, position:'center-center'}, header : { mode:'fit', height:800, quality:80, position:'center-center'}, mobile : { mode:'crop', width:640, height:1136, quality:60, position:'center-center'} }, globals : { telephone : '123456678', address : '42 Wallaby Way, Sydney' }, social : { facebook : 'http://www.facebook.com', twitter : 'http://www.twitter.com', linkedin : 'http://www.linkedin.com', youtube : 'http://www.youtube.com' } } %}


Is there a way to turn this into a usable PHP multidimensional array? Like this:

PHP:

$settings = array(
'theme' => '#91141b',
'transforms' => [
'thumb' => [ 'mode'=>'crop', 'width'=>300, 'height'=>300, 'quality'=>80, 'position'=>'center-center'],
'small' => [ 'mode'=>'fit', 'width'=>100, 'height'=>100, 'quality'=>70, 'position'=>'center-center'],
'header' => [ 'mode'=>'fit', 'height'=>800,'quality'=>80, 'position'=>'center-center'],
'mobile' => [ 'mode'=>'crop', 'width'=>640, 'height'=>1136,'quality'=>60, 'position'=>'center-center']
],
'globals' => [
'telephone' => '123456678',
'address' => '42 Wallaby Way, Sydney'
],
'social' => [
'facebook' => 'http://www.facebook.com',
'twitter' => 'http://www.twitter.com',
'linkedin' => 'http://www.linkedin.com',
'youtube' => 'http://www.youtube.com'
]
);


I wonder if there is a parser function I'm unaware of.

Thanks,

Mark

Answer

Ok, I sort of figured it out.

In the twig file, render out the settings variable with a json_encode filter:

{{ settings|json_encode|raw }}

Then in your PHP plugin you can render in the twig file and use PHP's json_decode.

$file = '_includes/settings';

$settings = json_decode(craft()->templates->render($file), true);
Comments