将Twig数组转换为PHP数组



使用file_get_contents我能够获得一个包含一个多维数组的小枝文件的内容:

枝:

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

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

谢谢,马克

好了,我算明白了。

在小枝文件中,使用json_encode过滤器呈现settings变量:

{{ settings|json_encode|raw }}

然后在你的PHP插件中,你可以在twig文件中渲染,并使用PHP的json_decode。

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

相关内容

  • 没有找到相关文章