php - 使用 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']
));
}
解决方案
不确定什么不适合你,但不要使用 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 传递给session
twig 并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);
推荐阅读
- azure - Azure 存储帐户备份循环
- azure - 为什么 App Insights 只显示警告和错误跟踪级别?低层怎么办?
- vbscript - 退出安全 CRT 脚本而不关闭应用程序或会话
- python - 图像数组的维度是 3D 而不是 Python 课程中的 2D
- html - HTML所需的表单验证没有给出任何警告
- javascript - TypeScript 函数重载不一致
- python - 我正在尝试在 django 中对数据进行排序,数据来自不同下拉列表中的不同表,但我被卡住了,我没有得到完美匹配
- scala - 如何为组件“将数据写入 HDFS 目录”编写 Scala 测试
- next.js - 在 NextJS 前端显示来自 Strapi API 的多个图像
- pandas - Pandas Pivot Table Repeating 1 Level of Index with No Rows