将Twig数组转换为PHP数组

时间:2016-08-22 09:52:50

标签: multidimensional-array twig

使用file_get_contents我能够获取仅包含一个多维数组的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'
  }
} %}

在PHP中,我现在可以使用此字符串:

{% 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' } } %}

有没有办法将其转换为可用的PHP多维数组?像这样:

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'
  ]
);

我想知道是否有一个我不知道的解析器函数。

谢谢,

标记

1 个答案:

答案 0 :(得分:0)

好的,我有点想通了。

在树枝文件中,使用json_encode过滤器渲染设置变量:

{{ settings|json_encode|raw }}

然后在您的PHP插件中,您可以在twig文件中呈现并使用PHP json_decode

$file = '_includes/settings';

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