Render Laravel 7 component programmatically

别说谁变了你拦得住时间么 提交于 2021-01-24 05:43:58

问题


I have a Laravel 7 component which looks like this

class Input extends Component
{
    public $name;
    public $title;
    public $value;
    public $type = 'text';

    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($name, $title)
    {
        $this->name = $name;
        $this->title = $title;
        $this->value = \Form::getValueAttribute($name);
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.fields.input');
    }
}

I can render the field in my Blade component like this:

<x-input name="name" :title="__('My field')" />

I have a requirement to create and render the field in code, I've tried the following:

$field = new Input('name', 'My field');
$field->render();

This returns an error:

Undefined variable: title

I can see that the render function is called but the public properties are not made available to the view. How would I render the component with the public properties?


回答1:


Manually add variables to the view. Otherwise it won't work

I reported this but it's not considered an issue:

https://github.com/laravel/framework/issues/32429




回答2:


Just add the properties to view manually and it will work. If not make the properties private but it should not have influence to that. Just my implementation.

     /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view(
            'components.fields.input',
            ['name' => $this->name, 'title' => $this->title]
        );
    }


来源:https://stackoverflow.com/questions/61484068/render-laravel-7-component-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!