【问题标题】:Interpolate Twig variable/attribute inside value of another Twig attribute definition在另一个 Twig 属性定义的值内插入 Twig 变量/属性
【发布时间】:2012-08-08 09:36:13
【问题描述】:

以如下结构为例:

{% set paths = {
                   ...
                   'js': {
                           ...
                           'jquery': {
                                      'version': '1.7.2',
                                      'cdn': 'https://ajax.googleapis.com/ajax/libs/jquery/{{paths.js.jquery.version}}/jquery.min.js',
                                      'fallback': ....
                                      }
                          }
               }
%}

要访问,我通常会使用以下内容:

 <script src="{{paths.js.jquery.cdn}}"></script>

问题:

无法识别内插变量,您会得到类似...libs/jquery/%7B%7B%paths.js/jquery.version7D%7D/jquery.min.js... 的信息。

我试过了:

  • 'a': 'text{{b}}text',
  • 'a': {{ ('text' ~ b ~ 'text') }},
  • 'a': "{{ ('text' ~ b ~ 'text') }}",
  • 'a': "{{ (['text', b, 'text'] | join }}",
  • 'a': "{{ (['text', {{b}}, 'text'] | join }}"
  • 还有更多我忘记了

我知道属性()

关于它的文档不多,但据我所知,它必须是这样的:

attribute(paths, attribute(js, attribute(jquery, cdn)))

对于一个级别来说可以,但不是任意级别的深度。如果我误解了attribute(),请纠正我。

【问题讨论】:

    标签: object twig interpolation templating templating-engine


    【解决方案1】:

    'a': ('text' ~ b ~ 'text') 实际上是正确的,但表达式周围不能有花括号(因为我们已经在表达式中,即变量定义中)。

    正确方法:

    {% set paths = {
                       ...
                       'js': {
                               ...
                               'jquery': {
                                          'version': '1.7.2',
                                          'cdn': ('https://ajax.googleapis.com/ajax/libs/jquery/' ~ paths.js.jquery.version ~ '/jquery.min.js'),
                                          'fallback': ....
                                          }
                              }
                   }
    %}
    

    但是这里有一个简单的设计错误;当渲染器/解析器到达cdn 属性定义时,paths 尚未设置。解决此问题的一种可能方法是先声明另一个变量;

    {% set params=  {
                       'jqueryversion': '1.7.2'
                    }
    %}
    
    {% set paths = {
                       ...
                       'js': {
                               ...
                               'jquery': {
                                          'cdn': ('https://ajax.googleapis.com/ajax/libs/jquery/' ~ params.jqueryversion ~ '/jquery.min.js'),
                                          'fallback': ....
                                          }
                              }
                   }
    %}
    

    很明显,如果paths.js.jquery.cdn 只会被使用一次,那么只需将 parent 变量的值硬编码到您需要的位置并插入 child 变量:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/{{params.jqueryversion}}/jquery.min.js"></script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多