Twig how to assign a JS variable to PHP variable

Viewed 31

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
2 Answers

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

Related