dry18813 2016-11-19 09:01
浏览 82
已采纳

如何以Twig形式访问$ _POST?

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') }}
  • 写回答

2条回答 默认 最新

  • douyan6742 2016-11-19 09:24
    关注

    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%}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面