【问题标题】:Right way to pass input data to blade template in Laravel?在 Laravel 中将输入数据传递给刀片模板的正确方法?
【发布时间】:2014-12-17 17:06:25
【问题描述】:

当我将 POST 数据传递给刀片模板时,这之间有什么区别吗:

Route::post('postpage', function()
{
    return View::make('postdata')->with('postData', Input::all());
});

还有这个?

Route::post('postpage', function()
{
    return View::make('postdata', array('postData'=> Input::all()));
});

或者两者都相同,我应该继续使用更短的语法?

【问题讨论】:

    标签: php laravel input laravel-4


    【解决方案1】:

    正如已经说过的那样,两者都会做同样的事情。不同之处在于,通过将方法链接到View 对象,您将能够实例化和操作View 对象,同时将数据链接到它,然后最终将其作为响应返回。 在现实生活中这种情况很少发生,所以在大多数情况下,两者都会达到相同的效果

    但是为了将输入数据传回视图,还有一个更简单的方法:

    return View::make('postdata')->withInput();
    

    通过使用withInput(),您之前的所有输入都将再次传递给视图。 然后,您可以通过在您的视图中使用 Input::old('email') 来访问它。

    确保在使用withInput() 之前,首先在控制器方法中调用Input::flash()Input::old() 从 Session Flashdata 中提取数据,这使得调用上述方法成为必要。 - 感谢 pc-shooter 提及。

    【讨论】:

    • 使用Input::old('email')需要在对应的controller中做Input::flash()
    • 糟糕。完全忘记了这一点。明天我在PC上时将其添加到答案中。谢谢
    【解决方案2】:

    它们完全一样。

    选择你最喜欢的。

    请注意,如果您愿意,也可以将数组传递给 with

    return View::make('postdata')->with([
        'postData' => Input::all(),
    ]);
    

    在这种特殊情况下,它没有多大意义,但是当传递大量数据时,您可能会喜欢这种方式。最终取决于您。

    【讨论】:

      【解决方案3】:

      使用魔法方法

      Route::post('postpage', function()
      {
          return View::make('postdata')->withPostdata(Input::all());
      });
      

      $postdata 可以从视图中访问

      【讨论】:

        猜你喜欢
        • 2019-01-06
        • 1970-01-01
        • 2018-10-13
        • 1970-01-01
        • 1970-01-01
        • 2018-12-09
        • 2019-08-01
        • 1970-01-01
        • 2013-06-01
        相关资源
        最近更新 更多