【问题标题】:Twig multiple variables and json_encodeTwig 多个变量和 json_encode
【发布时间】:2015-10-20 19:34:45
【问题描述】:

首先,我对 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;
}

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

【问题讨论】:

    标签: javascript symfony twig


    【解决方案1】:

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

    【讨论】:

      【解决方案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 }}'>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-19
        • 1970-01-01
        • 2017-09-23
        • 1970-01-01
        相关资源
        最近更新 更多