-3

I'm having the same problem as this thread how to assign javascript variable value to php variable however I'm using twig.

I need to catch a value from JS and pass it to a PHP variable.

What have I tried without success:

<script type="text/javascript">
    var display = localStorage.getItem('display');
    console.log(display); // Outputs correctly
    
    {% set temp = display %}
</script>
{{ temp }} // output: empty


{% set temp = "<script>localStorage.getItem('display')</script>" %}
{{ temp }} // output: <script>localStorage.getItem('display')</script>

<script>document.cookie = "display=" + localStorage.getItem('display')</script>
{{ app.request.cookies.get('display') }} // output: empty
ADyson
  • 57,178
  • 14
  • 51
  • 63
Linesofcode
  • 5,327
  • 13
  • 62
  • 116
  • 1
    https://craftcms.stackexchange.com/questions/21742/local-storage-in-twig – Reynadan Sep 23 '22 at 13:55
  • 2
    @Linesofcode Ivar is correct. You can't directly assign something to a PHP variable from JS. Since PHP runs on the server and JS runs on the client, any JS code will not be executed until after the entire PHP script has already completed. e.g. here's a silly demo: https://3v4l.org/oDSl5 . The PHP variable just contains the Javascript code snippet, not the result of executing that Javascript. The lifecycle is: http request from browser -> PHP runs, generates some HTML/CSS/JS/whatever content -> PHP script ends, output sent to browser -> browser loads content -> Javascript code is executed. – ADyson Sep 23 '22 at 14:01
  • 2
    ...so you can see, the JS cannot directly update PHP. To send something from the browser/JS environment back to PHP, you must initiate a new HTTP request and start the cycle over again. Remember that the web is a stateless, disconnected, client-server architecture. Client (browser) and server (PHP in this case) only talk to each other periodically by means of HTTP requests (and/or websocket messages, when applicable). The JS and PHP execute at different times and on different computers. – ADyson Sep 23 '22 at 14:02
  • P.S. The example in your question seems a little contrived, it's not really clear why you think you'd want/need to do that in a single request - you can already look at the cookies from JS and output the content there and then if needed. And obviously anything you put in a cookie will be sent to the browser when the next http request runs anyway, so it will reach PHP eventually. – ADyson Sep 23 '22 at 14:10

2 Answers2

1

you cant, because the twig will be rendered before sending to browser, so browser's localstorage is not even existing when twig is compiling

islemdev
  • 186
  • 1
  • 8
-1

It seems Twig does not allow such a thing: https://craftcms.stackexchange.com/questions/21742/local-storage-in-twig

Dharman
  • 30,962
  • 25
  • 85
  • 135
Linesofcode
  • 5,327
  • 13
  • 62
  • 116