【发布时间】:2013-11-26 09:08:45
【问题描述】:
我在我的 Laravel 控制器中使用 Post/Redirect/Get (PRG) 模式来防止重复提交表单。
当我不使用布局或我的布局不使用任何变量时,它运行良好。问题是我的布局使用了一个名为$title 的变量。当我加载视图和布局而不重定向它运行良好时,控制器中设置的标题被传递给布局,但是在处理表单并重定向到使用相同布局和相同控制器方法的相同路由后,我得到一个“未定义的变量:标题”来自我的布局文件的错误。
这是我的代码:
文件:app/routes.php
Route::get('contact', array('as' => 'show.contact.form', 'uses' => 'HomeController@showContactForm'));
Route::post('contact', array('as' => 'send.contact.email', 'uses' => 'HomeController@sendContactEmail'));
文件:app/controllers/HomeController.php
class HomeController extends BaseController {
protected $layout = 'layouts.master';
public function showContactForm()
{
$this->layout->title = 'Contact form';
$this->layout->content = View::make('contact-form');
}
public function sendContactEmail()
{
$rules = ['email' => 'required|email', 'message' => 'required'];
$input = Input::only(array_keys($rules));
$validator = Validator::make($input, $rules);
if($validator->fails())
return Redirect::back()->withInput($input)->withErrors($validator);
// Code to send email omitted as is not relevant
Redirect::back()->withSuccess('Message sent!');
}
}
文件:app/views/layouts/master.blade.php
<!DOCTYPE html>
<html>
<head>
<title>{{{ $title }}}</title>
</head>
<body>
@yield('body')
</body>
</html>
文件:app/views/contact-form.blade.php
@section('body')
@if (Session::has('success'))
<div class="success">{{ Session::get('success') }}</div>
@endif
{{
Form::open(['route' => 'send.contact.email']),
Form::email('email', null, ['placeholder' => 'E-mail']),
Form::textarea('message', null, ['placeholder' => 'Message']),
Form::submit(_('Send')),
Form::close()
}}
@stop
我不明白为什么重定向后下一行代码被忽略
$this->layout->title = 'Contact form';
我试过Redirect::action('HomeController@sendContactEmail'); 或Redirect::route('show.contact.form'); 但结果是一样的。
负责渲染那个view的controller在redirect前和redirect后是一模一样的,而且完全没有业务逻辑,为什么只适用于第一种情况而不能适用于第二种情况呢?
【问题讨论】:
标签: layout laravel laravel-4 post-redirect-get