【问题标题】:Returning a blade component from a controller in Laravel从 Laravel 中的控制器返回刀片组件
【发布时间】:2021-04-17 19:41:12
【问题描述】:

我正在运行 Laravel 7,我想知道是否可以从控制器返回渲染的 Blade 组件,就像使用视图一样。我可以像下面这样返回组件的视图。

return View::make('components.some-view');

但是,我无权访问 SomeView 组件类中的任何数据或方法。如果我尝试使用组件中定义的变量,则会收到未定义变量错误。

【问题讨论】:

    标签: php laravel laravel-blade laravel-7


    【解决方案1】:

    您可以使用view 函数从控制器渲染刀片组件:

    //first parameter = Path of your component
    //second argument = All your variables that your component receive 
    
    $html = view('components.yourComponentName', ['x-variable' => $value]);
    return $html; 
    

    【讨论】:

      【解决方案2】:

      在控制器中创建组件对象

      $com = new SomeComponent($variable1, $variable2);
      
      //call the render function
      $comHtml = $com->render();
      

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        试试这个,它在 Laravel 8 中对我有用

        例如我有 App\View\Components\Form\Button 组件

        <?php 
           class Button extends Component{
               public $variable1;
               public $variable2;
        
               public function __construct($variable1, $variable2){
                    $this->variable1 = $variable1;
                    $this->variable2 = $variable2;
               }
        
               public function render(){
                     // return view('view_component_name'); 
               }
           }
        ?>
        

        & 我想在没有视图布局的控制器中渲染该组件 那么我可以这样做

        <?php
          use App\View\Components\Form\Button;
        
          class TestController extends Controller{
        
             public function index(Request $request)
        
                $obj = new Button($variable1, $variable2);
                $obj->render()->with($obj->data());
             }
          }
        ?>
        

        **数据函数包括组件的方法、属性和属性。

        希望这篇文章对你有帮助

        【讨论】:

        • 为什么我的回答得到了反对票?我的答案是工作示例。我在我的项目中使用这种方式通过调用主视图或任何扩展视图来渲染特定的组件视图,那么它非常有用。
        【解决方案4】:

        使用 YourDirectory\some-view;

        $controllerObject = new some-view;

        $controllerObject -> 变量;

        【讨论】:

          猜你喜欢
          • 2021-08-16
          • 2018-03-24
          • 2019-09-23
          • 1970-01-01
          • 2019-02-06
          • 1970-01-01
          • 2020-07-04
          • 2023-03-26
          • 1970-01-01
          相关资源
          最近更新 更多