Twig 多个变量和 json_encode

Twig multiple variables and json_encode

首先,我对 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。但是我怎样才能将所有这些 settings/options 组合成可用于某个功能的东西呢?

像这样:

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

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

为什么不将 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);

您可以将 json_encode 过滤器与 twig 一起使用。

数据属性

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