首页 > 开发 > PHP > 正文

跟我学Laravel之视图 & Response

2024-05-04 22:18:23
字体:
来源:转载
供稿:网友

基本Response

从路由中返回字符串

代码如下:
Route::get('/', function()
{
    return 'Hello World';
});

创建自定义Response

Response类继承自Symfony/Component/HttpFoundation/Response类,提供了多种方法用于构建HTTP Response。

代码如下:
$response = Response::make($contents, $statusCode);

$response->header('Content-Type', $value);

return $response;

如果需要访问 Response 类的方法,但又要返回一个视图作为响应的内容,通过使用 Response::view 方法可以很容易实现:

代码如下:
return Response::view('hello')->header('Content-Type', $type);

在Response中添加Cookie

代码如下:
$cookie = Cookie::make('name', 'value');

return Response::make($content)->withCookie($cookie);

重定向

返回一个重定向

return Redirect::to('user/login');
返回一个带有数据的重定向

return Redirect::to('user/login')->with('message', 'Login Failed');
注意: with 方法将数据写到了Session中,通过Session::get 方法即可获取该数据。
返回一个重定向至命名路由

return Redirect::route('login');
返回一个重定向至带有参数的命名路由

return Redirect::route('profile', array(1));
返回一个重定向至带有命名参数的命名路由

return Redirect::route('profile', array('user' => 1));
返回一个重定向至控制器Action

return Redirect::action('HomeController@index');
返回一个重定向至控制器Action并带有参数

return Redirect::action('UserController@profile', array(1));
返回一个重定向至控制器Action并带有命名参数

return Redirect::action('UserController@profile', array('user' => 1));

视图

视图通常包含应用中的HTML代码,为分离表现层与控制器和业务逻辑提供了便利。视图存放于app/views目录。

一个简单视图案例:

代码如下:
<!-- View stored in app/views/greeting.php -->

<html>
    <body>
        <h1>Hello, <?php echo $name; ?></h1>
    </body>
</html>

通过如下方法来返回该视图到浏览器:

代码如下:
Route::get('/', function()
{
    return View::make('greeting', array('name' => 'Taylor'));
});

传递给View::make方法的第二个参数是一个数组,它将被传递给视图。

传递数据给视图

代码如下:
// Using conventional approach
$view = View::make('greeting')->with('name', 'Steve');

// Using Magic Methods
$view = View::make('greeting')->withName('steve');

在上面的案例中,$name变量在视图内是可以访问的,其值为Steve。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表