這篇文章主要介紹Laravel 自定義視圖組件的示例,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
Laravel 的視圖合成器可將數(shù)據(jù)與指定視圖綁定在一起,避免了重復(fù)編寫代碼。
View::composer('profile', 'App\Http\View\Composers\ProfileComposer');
由于數(shù)據(jù)的生成和渲染是分開進(jìn)行的,理解起來不夠直觀。因此,可以采用視圖組件的方式將兩者進(jìn)行封裝。
<?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 自定義視圖組件的示例”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
當(dāng)前名稱:Laravel自定義視圖組件的示例-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://aaarwkj.com/article14/ccjpde.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、關(guān)鍵詞優(yōu)化、外貿(mào)建站、網(wǎng)站內(nèi)鏈、自適應(yīng)網(wǎng)站、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容