欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

控制器 提取 获取 获得 得到模板内容 视图内容 到控制器 laravel get blade content to controller Get the rendered PHP blade template content – Laravel 5 有大用 有大大用

There was a scenario I recently encountered, whereby it was especially useful to retrieve the rendered contents of the PHP blade template in Laravel 5, before simply returning it to the browser. I wanted access to the HTML view as a string, that I could further manipulate myself, before returning it to the browser.

Let’s jump right in and say that our PHP blade template in Laravel lives at resources/views/sample.blade.php, and this is what the contents are made up of:

1
2
3
<div>
  <p>This is {{$name}}.</p>
</div>

We’ve got a simple route in app/Http/routes.php, which calls a method from our controller:

1
Route::get('/whoami', 'SampleController@getName');

And within our controller (app/Http/Controllers/SampleController.php), we call the all important render method on the returned view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
 
class SampleController extends Controller
{
  public function getName()
  {
    $contents = view('sample', ['name' => 'Code Chewing'])->render();
    // do some other manipulation?
    return $contents;
  }
}

The render method comes from the View class in vendor/laravel/framework/src/Illuminate/View/View.php.

You now have an opportunity to access the populated template, in string form, before handing it off to the browser.

来自 http://www.codechewing.com/library/get-rendered-blade-template-content-laravel-5/
 

获取渲染的PHP刀片模板内容 - Laravel 5

最近遇到了一种情况,因此在将其返回浏览器之前,检索Laravel 5中的PHP刀片模板的渲染内容特别有用。我希望以一个字符串的形式访问HTML视图,我可以进一步操纵自己,然后返回到浏览器。

我们跳进来,说我们在Laravel的PHP刀片模板生活在这里resources/views/sample.blade.php,内容是由以下组成:

1
2
3
<div>
  <p>This is {{$name}}.</p>
</div>

我们有一个简单的路由app/Http/routes.php,它调用了一个控制器的方法:

1
Route::get('/whoami', 'SampleController@getName');

在我们的controller(app/Http/Controllers/SampleController.php)中,我们render在返回的视图中调用所有重要的方法:

1
2
3
4
6
7
8
9
10
11
12
13
14
<?php
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
 
class SampleController extends Controller
{
  public function getName()
  {
    $contents = view('sample', ['name' => 'Code Chewing'])->render();
    // do some other manipulation?
    return $contents;
  }
}

render方法来自于View该类vendor/laravel/framework/src/Illuminate/View/View.php

您现在有机会以字符串形式访问填充的模板,然后将其移交到浏览器。

普通分类: