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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)