旗下导航:搜·么
当前位置:网站首页 > PHP框架 > Laravel > 正文

Laravel 自定义视图组件【laravel框架】

作者:搜搜PHP网发布时间:2019-11-27分类:Laravel浏览:76


导读:Laravel的视图合成器可将数据与指定视图绑定在一起,避免了反复编写代码。View::composer('profile','App\Http\View\Compos...
Laravel 的视图合成器可将数据与指定视图绑定在一起,避免了反复编写代码。

View::composer('profile', 'App\Http\View\Composers\ProfileComposer');

因为数据的生成和衬着是离开举行的,明白起来不够直观。因而,能够采纳视图组件的体式格局将二者举行封装。

<?php
namespace App\ViewComponents;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class ExampleComponent implements Htmlable
{
    private $color;
    private $request;
    public function __construct(Request $request, string $color)
    {
        $this->color = $color;
        $this->request = $request;
    }
    public function toHtml()
    {   
        return View::make('example')
            ->with('color', $this->color)
            ->render();
    }
}

在视图中运用

{{ app()->makeWith(App\ViewComponents\ExampleComponent::class,['color' => 'green'])->toHtml() }}

封装指令

Blade::directive('render', function ($expression) {
    list($class, $params) = explode(',', $expression, 2);
    $class = "App\\ViewComponents\\".trim($class, '\'" ');
    return "<?php echo app()->makeWith('$class', $params)->toHtml(); ?>";
});

运用指令

@render('ExampleComponent', ['color' => 'green'])

参考资料

spatie/laravel-view-components: A better way to connect data with view rendering in Laravel
Introducing View Components in Laravel, an alternative to View Composers - Laravel News

更多Laravel相干技术文章,请接见Laravel框架入门教程栏目举行进修!

以上就是Laravel 自定义视图组件的细致内容,更多请关注ki4网别的相干文章!

标签:Laravel