Meules
Meules

Reputation: 1389

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. And yes I'm pretty new to Twig :)

I'm trying to add some Twig variables to a javascript variable. That javascript variable is used to translate text to different languages.

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:

{{ 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. That's where my problems start.

How do you add tusp to that javascript variable?

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.

Any help greatly appreciated.

Upvotes: 2

Views: 3066

Answers (1)

Michael Ni&#241;o
Michael Ni&#241;o

Reputation: 467

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>

Upvotes: 2

Related Questions