2

I have a requirement which which might require me to set a new variable in TWIG for

  • {{ app.request.query }} i.e. ($_GET)
  • {{ app.request.request }} i.e. ($_POST)
  • {{ app.request.session }} i.e. ($_SESSION)
  • {{ app.request.cookies }} i.e. ($_COOKIE)

e.g. {% app.request.query.set('myvariable':'value' %} ...

3
  • Why do you need to do that? There has to be a better solution.
    – Maerlyn
    Mar 18, 2017 at 14:03
  • 1
    @Maerlyn I have a twig file in which I have to use a twig variable set in the {body block} in my {javascript block}. As the blocks limit the scope of variables and setting the variable globally does not let me get the value from within the {body block} into my {javascript block}, I have to find alternatives to get what I need done. Hence the usage of set/add for request/session in twig. Mar 18, 2017 at 14:46
  • 2
    That kind of logic should go in your controller, or a twig extension.
    – Maerlyn
    Mar 18, 2017 at 19:46

2 Answers 2

5

If you want to set the variable while in TWIG here is what I know:

For $_POST variables use this :
{{ app.request.request.add(['var1', 'data1']) }}
{{ app.request.request.get(0) }}
{{ app.request.request.get(1) }}

For $_GET variables use this :
{{ app.request.query.add(['var2', 'data2']) }}
{{ app.request.query.get(0) }}
{{ app.request.query.get(1) }}

For $_COOKIE variables use this :
{{ app.request.cookies.add(['var3' , 'data3']) }}
{{ app.request.cookies.get(0) }}
{{ app.request.cookies.get(1) }}

For $_SESSION variables use this :
{{ app.session.set('var4', 'data4') }}
{{ app.session.get('var4') }} <!-- shows 'data4 -->
Or
{{ app.request.session.set('var4', 'data4') }}
{{ app.request.session.get('var4') }} # shows 'data4
1
  • This is what I was looking for. I will wait to accept this answer for a day for two so that if someone else wants to add more information they have a chance. Mar 18, 2017 at 13:45
-1

You can easy append element to the array before calling Twig->render in PHP.

Simply write

$_GET['myvariable'] = $value
1
  • 1
    Thank you for your answer, but I am looking for an answer to set the variables from within TwigBundle (Symfony). Mar 18, 2017 at 13:43

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.