【问题标题】:Laravel Blade how to pass $attributes to component from controllerLaravel Blade 如何将 $attributes 从控制器传递给组件
【发布时间】:2021-08-19 09:22:45
【问题描述】:

我有一个包含$attributes 的刀片组件;当组件从另一个刀片模板调用但从控制器通过view() 调用时,这将是一个属性包,$attributes 未定义!如何从控制器以$attributes 的形式传递数据?

组件:sample

<div {{ $attributes->except('content') }}>{{ $content }}</div>

模板:效果很好。

...
<x-sample class="test" content="test"/>
...

控制器:错误未定义的变量 $attributes

$attributes = ['class' => 'test', 'content' => 'test'];
view('components.sample', $attributes)->render();
view('components.sample', ['attributes' => $attributes])->render();
view('components.sample')->with($attributes)->render();

更新(解决方案):

有效:

view('components.sample', [
    'prop1' => '...',
    'prop2' => '...',
    'attributes' => new ComponentAttributeBag(['attr1' => '...', 'attr2' => '...']),
])->render();

【问题讨论】:

  • 您为什么要尝试将组件呈现为来自控制器的视图?这种方式违背了组件的意义
  • 数据嵌套复杂,我更喜欢把逻辑放在控制器中,在视图层使用模板引擎。
  • 复杂用户界面的诀窍是使用简化它的东西。如果事情真的变得复杂,我会建议研究 VUE.js。它并不完美,但比您当前的解决方案更好(尝试)
  • 似乎可以通过组件 php 类。我认为可能有一个直接的解决方案;)

标签: laravel laravel-blade laravel-8


【解决方案1】:

发生的事情是组件从视图继承变量,例如,如果您从主视图定义变量,它应该在该视图的组件中工作。然后,当您将视图包含到 about 页面时,将无法识别变量,因为它们不是从 about 视图继承的。在 Laravel 中,您不能将数据直接从控制器传递到组件。但是laravel已经通过View Composer解决了。

由于我不喜欢太多复杂的内容,尤其是对于提供程序,我编辑了我的AppServiceProvider,您可以创建自己的提供程序。

YourServiceProvider 在我的情况下AppServiceProvider 在 boot() 函数中,您可以使用三个选项之一。我推荐第三个,因为它很干净

public function boot()
    {
        // option1 -  Every single view
         View::share('shops', Shop::orderBy('name')->get());

        // option2 - Gradular views with wildcards
         View::composer(['client.*'], function ($view){
             $view->with('shops', Shop::orderBy('name')->get());
         });

        // option3 - Dedicated class

        View::composer(['client.includes.*','client.create-product','client.cart'], ShopsComposer::class);
         View::composer(['client.includes.*','client.cart'], CartComposer::class);
    }

如果你使用第三种方法,你必须创建ViewComposer

<?php

namespace App\Http\View\Composers;

use App\Models\CartItem;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;

class ShopsComposer
{
    public function compose(View $view){
        $shop = auth()->user()->shops->sortBy('name');
        $cartItem = new CartItem();
        $cartCount = 0;
        if (Session::has('cartId')) {
            $carts = Session::get('cartId');
            $cartItems = $cartItem->with('products')->where('cart_id', '=', $carts->id)->get();
        foreach ($cartItems as $item) {
            $cartCount += $item->quantity;
            }
        } 
        $view->with('shopsComposer', $shop)->with('cartCount', $cartCount);
    }
}

您在此处定义的变量将可用于所有视图。包括组件。由于组件从视图文件中继承变量。

很抱歉,我不得不分享我的工作示例,因为我的时间不多了。如果我能很好地理解你的问题,我希望它能起作用。

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 2017-07-20
    • 2022-06-30
    • 2015-01-23
    • 2021-06-11
    • 2018-03-18
    • 2020-10-16
    • 1970-01-01
    相关资源
    最近更新 更多