CI4中如何在视图中显示redirect()->to()->with()传递的闪存数据
解决方案
针对CodeIgniter 4版本
你的重定向代码写法是正确的,但视图里的session调用要适配CodeIgniter的规则,同时要确保项目已正确配置Session服务(默认配置已生效,可检查app/Config/App.php里的sessionDriver相关设置)。
视图里正确的调用方式有两种:
- 用session判断并获取数据:
<?php if (session()->has('msg')) : ?> <div><?= esc(session()->get('msg')) ?></div> <?php endif; ?>
- 专门获取flash类型的一次性数据(
redirect()->with()默认设置的就是这类会自动销毁的flash数据):
<?php $msg = session()->getFlashdata('msg'); if ($msg) : ?> <div><?= esc($msg) ?></div> <?php endif; ?>
针对CodeIgniter 3版本
CI3不支持redirect()->to()->with()的链式写法,需要先设置flashdata再执行重定向:
$this->session->set_flashdata('msg', 'You are not allowed to access that category.'); redirect(base_url('categories'));
然后在视图里这样调用:
<?php if ($this->session->flashdata('msg')) : ?> <div><?= $this->session->flashdata('msg') ?></div> <?php endif; ?>
通用注意事项
- CI4:确保全局
session()函数可正常使用,或已通过use CodeIgniter\Session\Session;引入Session类。 - CI3:确保控制器继承了
CI_Controller,且application/config/autoload.php里已自动加载session库($autoload['libraries'] = array('session');)。
内容的提问来源于stack exchange,提问作者elimariaaa
相关产品推荐
相关产品推荐

