简体   繁体   English

树枝中的树枝变量

[英]Twig variable in string

First of all I don't have the abillity to create custom functions of somekind. 首先,我没有能力创建某种自定义函数。 My question need to be done with the frontend options of Twig. 我的问题需要使用Twig的前端选项来完成。 And yes I'm pretty new to Twig :) 是的,我是Twig的新手:)

I'm trying to add some Twig variables to a javascript variable. 我正在尝试将一些Twig变量添加到javascript变量中。 That javascript variable is used to translate text to different languages. 该javascript变量用于将文本翻译成不同的语言。

The end result need to be: 最终结果必须是:

var ajaxTranslations = {{ 'Free shipping; In stock; Natural; Juice;' | t_json | raw }}; 
// so Natural and Juice need to added in the exact same way as above

So I have a Twig variable that have some text in it like so: 所以我有一个Twig变量,里面有一些文本,如下所示:

{{ product_usp }} // results in -> Natural, Juice

So first I want to split that string (after each comma) into two seperate values. 因此,首先我想将该字符串(在每个逗号之后)分成两个单独的值。 Next I want to create an array with those values and add them to that javascript variable. 接下来,我想用这些值创建一个数组并将它们添加到该javascript变量中。 That's where my problems start. 这就是我的问题开始的地方。

How do you add tusp to that javascript variable? 如何将tusp添加到该javascript变量?

What I did is this: 我所做的是:

 {% set tusp = [] %}
  {% set usps = theme.product_usp | split(',') %}

  {% for usp in usps %}
   {% set tusp = usp ~ ';' %}
  {% endfor %}

<script>
    var ajaxTranslations = {{ 'Free shipping; In stock; ~ tusp' | t_json | raw }};
<script>

This results in empty value or ~ tusp is seen as text instead of a value. 这将导致值为空或~ tusp被视为文本而不是值。

Any help greatly appreciated. 任何帮助,不胜感激。

When you use the tilde operator it must be located in between a string(s) and/or a variable(s): 使用代字号运算符时,它必须位于字符串和/或变量之间:

<script>
    var ajaxTranslations = "{{ 'Free shipping; In stock; ' ~ tusp | raw }}";
<script>

Or you can use "string interpolation": 或者,您可以使用“字符串插值”:

<script>
    var ajaxTranslations = "{{ "Free shipping; In stock; #{tusp}" | raw }}";
<script>

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

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