简体   繁体   English

在Twig中将变量值和键名与句号/句点进行比较

[英]Comparing variable values and key names with full stops/periods in Twig

My CakePHP view element for outputting a script tag has a variable called scriptsGroup with a value of, for example, main passed to it. 我用于输出脚本标记的CakePHP视图元素具有一个名为scriptsGroup的变量,其值例如为传递给它的main

Twig: 枝条:

{{ dump(scriptsGroup) }}

Output: 输出:

string(4) "main"

I also have the following view array called busters . 我也有以下称为busters视图数组。

Twig: 枝条:

{{ dump(busters) }}

Output: 输出:

object(stdClass)#134 (2) {
  ["public/js/build/main.js"]=>
  string(8) "7e9a1c32"
  ["public/css/main.css"]=>
  string(8) "d41d8cd9"
}

In Twig, how can I check that the script referred to by the scriptsGroup variable (in this case, main ) is in the busters array, and, if it is, output a script tag with the relevant hash in the filename. 在枝条,我怎样才能检查脚本由称为scriptsGroup变量(在这种情况下, main )是在busters阵列,并且,如果是,输出与在文件名的有关散列的脚本代码。

Example of desired output: 所需输出示例:

<script src="/js/build/main_rev-7e9a1c32.js"></script>

I don't know how to deal with the array keys having full stops/periods and how to match the variable with the key of the array. 我不知道如何处理具有句号/句号的数组键,以及如何将变量与数组的键匹配。 I've tried the #{} interpolation syntax but am failing. 我尝试使用#{}插值语法,但失败了。

Update: I've tried using ~ : 更新:我尝试使用~

{% if busters['public/js/build/' ~ scriptsGroup ~ '.js'] %}

gives Impossible to access a key "public/js/build/main.js" on an object of class "stdClass" that does not implement ArrayAccess interface . 允许Impossible to access a key "public/js/build/main.js" on an object of class "stdClass" that does not implement ArrayAccess interface

Update 2: I realised I wasn't properly using PHP's json_decode function - it's now converting to an associative array so my new if condition is working. 更新2:我意识到我没有正确使用PHP的json_decode函数-它现在正在转换为关联数组,因此我的新if条件可以正常工作。 I just need to output the script tag now. 我现在只需要输出脚本标签。

{% if busters['public/js/build/' ~ scriptsGroup ~ '.js'] %}
    <script src="/js/build/{{ scriptsGroup }}_rev-{{ busters['public/js/build/' ~ scriptsGroup ~ '.js'] }}.js"></script>
{% endif %}

It uses the [] and ~ operators . 它使用[]~运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM