【问题标题】:Twig - JavaScript booleansTwig - JavaScript 布尔值
【发布时间】:2014-12-15 11:27:49
【问题描述】:

是否有一个 twig 函数可以让我将包含 PHP 布尔值的变量转换为文字 JavaScript 布尔值?

目前,我的 PHP 值“true”在我的 twig 模板中转换为“1”。 我已经尝试了一些转义函数,但到目前为止没有任何效果。

【问题讨论】:

    标签: javascript php types twig


    【解决方案1】:
    <script>
      // You can use it in literal code like this:
      var myBool = {{ mySuppliedValue ? 'true' : 'false' }};
    
      // Or in clientside string constants like this:
      console.log('The value is {{ mySuppliedValue ? 'true' : 'false' }}');
    </script>
    

    See the docs.

    【讨论】:

    • 第二个 Twig 调用应该是 myBool,因为您已经检索到它。
    • @DissidentRage 我的目的是展示一些示例用法。在第二种情况下,我不能按照您的建议使用 {{ myBool }} - 那时该变量存在于 JS 中,而不是 Twig 中。
    • 是的,就用console.log('The value is ' + myBool);
    • 这有点违背了给出多个例子来说明如何从 Twig 的末端整合它的意义......
    【解决方案2】:

    你可以使用json:

    <script>
      var myBool = {{ mySuppliedValue | json_encode }};
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2015-07-13
      • 2014-12-11
      • 2019-10-20
      相关资源
      最近更新 更多