user4975696 user4975696 - 16 days ago 4
Twig Question

How to access $_POST in Twig form?

I'm trying to print the value of the input field 'gameTitle' in Twig.

This is my code:

<h1>New game</h1>
<form method="post" action="">
<label>Game Title</label>
<input type="text" value="Monopoly" name="gameTitle"><br>
<input class="btn btn-success" name="submit" type="submit" value="Add game">
</form>
{% if app.request.post('submit') %}
{{ app.request('gameTitle')}}
{% endif %}


I've also tried:

{{ app.request.parameter.post('gameTitle}


As a result I want to print this result: "gameTitle is Monopoly".

My question, how do I do the following PHP code in Twig?

<?php
echo "gameTitle is ".$_POST['gameTitle'];
?>


Update:
- I'm not using Symfony, just Twig: http://twig.sensiolabs.org/
This does not work for me:

{{app.request.post('gameTitle')}}
{{app.request.request.get('gameTitle')}}
{{ app.request.request.get("gameTitle") }}
gameTitle is {{ app.request.request.post('gameTitle') }}

Answer

As far as I can see, the vanilla Twig doesn't provide access to the request variables by default. You should pass them to the template explicitly, e.g.:

require __DIR__ . '/vendor/autoload.php';

$loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');
$twig = new Twig_Environment($loader, array(
    'cache' => __DIR__ . '/tpl_cache',
));

echo $twig->render('template.twig', ['post' => $_POST]);

Then use it as follows:

{% if post.gameTitle is defined %}
Game title: {{ post.gameTitle }}
{% endif%}
Comments