-1

My question is similar to this one:

variable Twig in Javascript

Except that I want to use a variable (value) from a Javascript to use with Twig

I have this simple script:

<script type="text/javascript" charset="utf-8">
var test = "1";
</script>

I want to use that var test variable with my Twig page, to compare with another value that I already set in my controller and can use in the Twig page.

3
  • 2
    You can't, because your server-side Twig template is long done parsing by the time your client-side JavaScript runs. If you want to get a value from the client to the server, then you need to make an additional HTTP request (link, form, AJAX.) Commented Oct 20, 2017 at 23:26
  • What would be your use-case? Why do you need that? Commented Oct 20, 2017 at 23:40
  • It can't be a form or be sent to the server. That's why I thought if I could somehow use the JS value in Twig Commented Oct 23, 2017 at 14:07

1 Answer 1

0

As has already been said, Twig runs in PHP on the server and the JavaScript variable is on the client. To use it in a server-side template, you'd need to get the variable value back to the server using an AJAX request and then use that response to replace the content in the browser.

A potential way to do what you're asking is to use a JavaScript implementation of Twig like twig.js. This would allow your Twig templates to use JavaScript variables without having to go back to the server.

<script src="https://cdnjs.cloudflare.com/ajax/libs/twig.js/0.8.9/twig.min.js">
</script>
<script type="text/javascript" charset="utf-8">
  var test = "1";
  var template = twig({
    data: 'The value of test is {{ test }}.'
  });
  document.getElementById('some-element').innerHTML = template.render({ test: test });
</script>

I have a feeling that this is overkill for your purposes. It really depends what your use case is and what you're trying to achieve.

Sign up to request clarification or add additional context in comments.

3 Comments

My case is that if the value of test (javascript) is equal to '1', show the page, else show nothing. That's why I need to grab that value in Twig, so that I can do everything in Twig without going back to the server.
Like, if use var test '1' like this: {% if test == number %} do something... {%endif%}
What value do you need that you can't get on the server? Checking something about the client? If so you can probably get it from the request headers on the server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.