1

Im trying to put my code in a included theme.js file. It wont recognize my variables anymore.

Working in .rain file within the html code:

<script>
  jQuery(document).ready(function(){
    var uspicon1 = "{{ theme.usp_1_icon }}";
    var uspicon2 = "{{ theme.usp_2_icon }}";
    var uspicon3 = "{{ theme.usp_3_icon }}";
    var uspicon4 = "{{ theme.usp_4_icon }}";
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);  
    jQuery('.icon3').addClass(uspicon3);  
    jQuery('.icon4').addClass(uspicon4); 
  });
</script>

Not working with an include .js file:

  jQuery(document).ready(function(){
    var uspicon1 = "{{ theme.usp_1_icon }}";
    var uspicon2 = "{{ theme.usp_2_icon }}";
    var uspicon3 = "{{ theme.usp_3_icon }}";
    var uspicon4 = "{{ theme.usp_4_icon }}";
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);  
    jQuery('.icon3').addClass(uspicon3);  
    jQuery('.icon4').addClass(uspicon4); 
  });

Practicly the same without the script tags. I tested a console.log() and it works fine. I'm guessing it wont recognize my {{ variables }} in .js file.

Anybody know what the syntax is?

4

There is no "syntax" for it since you don't parse these files with PHP. You'll have to declare your variables inside a twig file

First Approach

Twig

<script>
    var myVariable = {{ theme|json_encode|raw }}
</script>

Javascript

jQuery(document).ready(function(){
    var uspicon1 = myVariable.usp_1_icon;
    var uspicon2 = myVariable.usp_2_icon;
    var uspicon3 = myVariable.usp_3_icon;
    var uspicon4 = myVariable.usp_4_icon;
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);  
    jQuery('.icon3').addClass(uspicon3);  
    jQuery('.icon4').addClass(uspicon4); 
});

Second Approach

Or you move your Javascript inside a Twig file

{% js %}
jQuery(document).ready(function(){
    var uspicon1 = "{{ theme.usp_1_icon }}";
    var uspicon2 = "{{ theme.usp_2_icon }}";
    var uspicon3 = "{{ theme.usp_3_icon }}";
    var uspicon4 = "{{ theme.usp_4_icon }}";
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);
    jQuery('.icon3').addClass(uspicon3);
    jQuery('.icon4').addClass(uspicon4);
});
{% endjs %}

You can as well attach the attributes in your html - that makes it much easier

Third Approach

Twig

<div class="icon4" data-icon="{{theme.usp_4_icon}}"></div>

Javascript

var element = jQuery('.icon4')
element.addClass(element.data('class'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.