Laravel中常用的几种向视图传递变量的方法

向视图中传递变量

我们在开发web应用当中,通常都不是为了写静态页面而生的,我们需要跟数据打交道,那么这个时候,问题就来了,在一个MVC的框架中,怎么将数据传给视图呢?比如我们要在 ArticleControllerindex 方法的视图输出一个 $title 的变量,在Laravel中,有下面几种常见的方法:

使用with()方法

public function index()
{
  $title = '文章标题1';
  return view('articles.lists')->with('title',$title);
}

这样的 with('title',$title) 中,第一个 'title' 就是key,第二个 $title 就是值,这样我们就可以在我们的 articles/lists.blade.php 中输出这个变量了:

<body>
  <h1><?php echo $title; ?></h1>
</body>

刷新我们的 blog.dev ,就可以看到类似这样的页面了:

image

而在blade引擎中,我们可以这样输出变量:

<body>
  <h1>{{ $title }}</h1>
</body>

其实在blade引擎中, {{ $title }} 会被解析为类似 这样的输出 <?php echo $title; ?> ,不过这里的 {{ }} 符号会将数据原样输出,比如你将 $title 写成这样:

public function index(){
  $title = '<span style="color: red">文章</span>标题1';
  return view('articles.lists')->with('title',$title);
}

这个时候你用 {{ $title }} 输出,会看到类似下面这样:

image

如果你想将 $title 作为页面元素渲染输出,你需要这样写:

<h1>{!! $title !!}</h1>
image

这里的 {{ }}{!! !!} 是blade的最基础的用法,这两个我们会用得特别多,后面我会详细说说blade的用法。

直接给view()传参数

使用这个方法的时候,你可以这样写:

public function index(){
  $title = '<span style="color: red">文章</span>标题1';
  return view('articles.lists',['title'=>$title]);
}

刷新页面,你依然会看到一样的输出。这里需要说明一下,如果你传多个变量,比如:

public function index()
{
  $title = '<span style="color: red">文章</span>标题1';
  $intro = '文章一的简介';
  return view('articles.lists',[                                                  
     'title'=>$title,
     'introduction'=>$intro
  ]);
}

在传递的数组中:

[
  'title'=>$title,
  'introduction'=>$intro
]

每一个key会在视图中作为变量,而 value 就作为变量的值。所以在视图中我们需要这样输出:

<body>
  <h1>{!! $title !!}</h1>
  <p>{{ $introduction }}</p>
</body>

这里应写成 {{ $introduction }} ,而不是 {{ $intro }}

使用compact

使用compact是这样写的:

public function index(){
  $title = '<span style="color: red">文章</span>标题1';
  $intro = '文章一的简介';
  return view('articles.lists',compact('title','intro'));
}

compact() 的字符串可以就是变量的名字,多个变量名用逗号隔开。这个时候注意更改视图的变量输出。

以上就是Laravel中常用的几种向视图传递变量的方法。

原文:https://www.jianshu.com/p/318bdb95ea41

posted @ 2020-01-10 17:22  橱窗外的小孩  阅读(1489)  评论(0编辑  收藏  举报