【ThinkPHP】5.1 完全开发手册 / 视图过滤

视图过滤

可以对视图的渲染输出进行过滤

<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
public function index()
{
// 使用视图输出过滤
return $this->filter(function($content){
return str_replace("\r\n",'<br/>',$content);
})->fetch();
}
}

如果需要进行全局过滤,你可以在初始化方法中使用:

<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
protected function initialize()
{
$this->view->filter(function($content){
return str_replace("\r\n",'<br/>',$content);
});
}

public function index()
{
// 使用视图输出过滤
return $this->fetch();
}
}

如果使用view助手函数进行模板渲染输出的话,可以使用下面的方式

<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
public function index()
{
// 使用视图输出过滤
return view()->filter(function($content){
return str_replace("\r\n",'<br/>',$content);
});
}
}