1

I am not sure how I can pass a variable from my JS folder to my Twig templates. It is a variable that takes true/false on page load and needs to be used inside an If statement to execute responsive code.

I tried calling the name of the variable itself but as I found out that doesn't work.

JS Script

var isMobile = (function() {....})();

Twig template

 {% if isMobile %}
  <div>Small div</div>
  {% else %}
  <div>Big div</div>
 {% endif %}
Kostis
  • 119
  • 1
  • 12

1 Answers1

0

It will be better and more convenient doing with Javascript itself.

<div id="yourDIV">
  This is my DIV element.
</div

In Javascript do something like this.

 var el = document.querySelector('#yourDIV');//to target multiple divs use class
 if (isMobile()) {
   el.style.display = "block";
  } else {
    el.style.display = "none";
 }

This is an idea, you can modify it as per your need.

sujeet
  • 3,480
  • 3
  • 28
  • 60
  • It is a lot of code that needs to be squeezed into JS including Twig syntax and I am not sure if that is wise to do. – Kostis Jun 26 '19 at 07:21
  • 2
    @Kostis Twig is PHP, Javascript and PHP can't communicate directly they can only with AJAX. For more information on the topic have a look https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php – sujeet Jun 26 '19 at 07:25