首页 > 解决方案 > 使用 Twig 将 $_SESSION 设置为输入值

问题描述

我正在制作注册表单,我希望在输入数据不正确的情况下重置页面,但我也不希望输入的数据消失。问题是我不知道如何使用 Twig 来做到这一点。所以我做这样的事情:

$_SESSION['fr_firstName'] = $firstName;

然后我想在输入值中输入这个名称。在我的 index.php 中,我有:

<?php
    session_start();

    require_once 'lib/Twig/Autoloader.php';
    Twig_Autoloader::register();

    $loader = new Twig_Loader_Filesystem('temp');
    $twig = new Twig_Environment($loader);

    if(isset($_SESSION['fr_firstName']))
    {

    }

    echo $twig->render('index.html', array(
        'fr_firstName' => ''
    ));
?>

在我的 index.html 中是:

<form action="register.php" method="post">
<input type="text" placeholder="First Name" value="{{ fr_firstName }}">
<input type="submit" class="reg" value="Sign Up"/>
</form>

在我的 register.php 中是:

<?php
    session_start();
    $firstName = $_POST['firstName'];
    //another thinks
    $_SESSION['fr_firstName'] = $firstName;
    //another thinks
    require_once "connect.php";
    //another thinks
    $connection = new mysqli($host, $db_user, $db_password, $db_name);
    //another thinks
    header('Location: index.php');
    //another thinks

好的,这是我的问题。如何将(在 index.php 中)$_SESSION['fr_firstName'] 设置为 index.html 中的输入值?

我的意思是这样的:

if(isset($_SESSION['fr_firstName']))
{
echo $twig->render('index.html', array(
        'fr_firstName' => $_SESSION['fr_firstName']
    ));
}

标签: phpsessiontwig

解决方案


不确定什么不适合你,但不要使用 if 来包围你的渲染,你应该去

    echo $twig->render('index.html', [
        'fr_firstName' => isset($_SESSION['fr_firstName']) ? $_SESSION['fr_firstName'] : '',
    ]);


如果您使用的是PHP 7.X.X版本,您可以使用空合并运算符

    echo $twig->render('index.html', [
        'fr_firstName' => $_SESSION['fr_firstName'] ?? '',
        'fr_Name'      => $_SESSION['fr_Name'] ?? '',
        'fr_Email'     => $_SESSION['fr_Email'] ?? '',
        /** etc.... **/
    ]);


另一种方法是将整个 -array 传递给sessiontwig 并default在模板中使用过滤器,例如

echo $twig->render('index.html', array_merge([
    'some_var' => 'var',
    'foo'      => 'bar',
], $_SESSION));
<input name="fr_firstName" value="{{ fr_firstName | default('') }}" />

如果您真的想使用完整的if符号,U 会使用类似以下的内容

$parms = [];
if (isset($_SESSION['fr_firstName'])) $parms['fr_firstName'] = $_SESSION['fr_firstName'];
if (isset($_SESSION['fr_Name'])) $parms['fr_Name'] = $_SESSION['fr_Name'];
if (isset($_SESSION['fr_Email'])) $parms['fr_Email'] = $_SESSION['fr_Email'];

echo $twig->render('index.html', $parms);

推荐阅读