user4975696 user4975696 - 1 year ago 145
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">
{% if'submit') %}
{{ app.request('gameTitle')}}
{% endif %}

I've also tried:


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

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

echo "gameTitle is ".$_POST['gameTitle'];

- I'm not using Symfony, just Twig:
This does not work for me:

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

Answer Source

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%}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download