Javascript Twig多变量和json_编码

Javascript Twig多变量和json_编码,javascript,symfony,twig,Javascript,Symfony,Twig,首先,我对小树枝很陌生。 我正在使用一个模板系统,以便用户可以设置一些选项来自定义模板。类似Shopify的东西 我想知道是否有可能获取所有设置并将它们发送到javascript函数以进一步处理它 假设用户可以设置以下选项: {{ theme.hide_label }} // option to show/hide a label {{ theme.label_color }} // option to set a color for the label 我可以这样做,然后获取这些变量并在js

首先,我对小树枝很陌生。 我正在使用一个模板系统,以便用户可以设置一些选项来自定义模板。类似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_编码的文章。但是,我如何将所有这些设置/选项组合成可用于某个函数的内容呢

大概是这样的:

var themeFunctions = {{ theme.label; theme.hidelabel; | t_json | raw }}
我见过有人用细枝翻译了很多文本:

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;
}

可以对非纯文本的变量执行类似的操作吗?

为什么不将json传递给视图

控制器动作:

    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);
你可以用细枝过滤

数据属性

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

内部脚本块

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

var-themeSetting=JSON.parse(“{theme}JSON|u encode | raw}”);
隐藏输入

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

若你们们的主题变量是普通对象,你们们可以直接编码,若你们们不想或者你们们想让变量使用白名单并创建新的变量,然后编码它

{% set themeSetting = {
    foo : theme.foo,
    label_color : theme.label_color,
    username: theme.user.name
}|json_encode %}
<body data-theme-setting='{{ themeSetting|raw }}'>
{%set themeSetting={
foo:theme.foo,
label\u color:theme.label\u color,
用户名:theme.user.name
}|json_encode%}