Twig多个变量和json_encode

时间:2015-07-29 17:10:33

标签: javascript symfony twig

首先,我对Twig很新。 我使用模板系统,以便用户可以设置一些选项来自定义模板。与Shopify类似的东西。

我想知道是否有可能获取所有设置并将它们发送到javascript函数以进一步处理它。

假设用户可以设置以下选项:

{{ theme.hide_label }} // option to show/hide a label
{{ theme.label_color }} // option to set a color for the label

我可以做这样的事情然后抓住这些变量并在js函数中使用它们:

 var hideLabel = '{{ theme.hide_label }}'; //true or false
 var labelColor = '{{ theme.label_color }}'; // #000000

不幸的是,我有很多设置,所以这将是一个很长的列表。

我已经阅读了json_encode。但是,如何将所有这些设置/选项分组为可用于函数的东西?

这样的事情:

var themeFunctions = {{ theme.label; theme.hidelabel; | t_json | raw }}

我已经看到有人用Twig翻译了大量文本:

var translations = {{ 'Add; Wishlist; Information; Add to wishlist;' | t_json | raw }};

然后创建了一个像这样的函数:

function getAjaxTranslation(key) {
  var translation;
  if (translation = eval('translations["' + key + '"]')) {
    return translation;
  }
  return key;
}

对于非纯文本的变量,可以做类似的事情吗?

2 个答案:

答案 0 :(得分:2)

您可以在树枝上使用json_encode过滤器。

数据属性

<body data-theme-setting='{{ theme|json_encode|raw }}'>

内部脚本块

<script type="text/javascript">
    var themeSetting = JSON.parse('{{ theme|json_encode|raw }}');
</script>

隐藏输入

<input type="hidden" id="themeSetting" value='{{ theme|json_encode|raw }}' />

如果你的主题变量是普通对象,你可以直接编码,如果没有,或者你想为变量设置白名单,使用set并创建新变量然后对其进行编码。

{% set themeSetting = {
    foo : theme.foo,
    label_color : theme.label_color,
    username: theme.user.name
}|json_encode %}
<body data-theme-setting='{{ themeSetting|raw }}'>

答案 1 :(得分:0)

为什么不将json传递给视图?

controlleraction:

    public function blaAction(){
       $theme= $themegetter->get('it');

        return array(
          "theme"=>$theme,
          "themejson"=> @json_decode(@json_encode($theme),1)
        )
    }

和js

var themejson = {{themejson}}


console.dir(themejson)
console.log(themejson.label);
相关问题