以编程方式渲染Laravel 7组件
我有一个Laravel 7组件,看起来像这样以编程方式渲染Laravel 7组件,laravel,laravel-blade,laravel-7,Laravel,Laravel Blade,Laravel 7,我有一个Laravel 7组件,看起来像这样 class Input extends Component { public $name; public $title; public $value; public $type = 'text'; /** * Create a new component instance. * * @return void */ public function __constr
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');
}
}
我可以在刀片组件中渲染字段,如下所示:
我需要在代码中创建和呈现字段,我尝试了以下方法:
$field = new Input('name', 'My field');
$field->render();
这将返回一个错误:
未定义变量:title
我可以看到调用了render函数,但视图无法使用公共属性。如何使用公共属性呈现组件?手动将变量添加到视图中。否则就不行了 我报告了这一点,但不认为这是一个问题:
只需手动添加要查看的属性即可。如果不将财产私有化,但不应对其产生影响。只是我的实现
/**
* 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]
);
}
试试这个,它在Laravel8中对我有效,我检查了Laravel7中存在的
data
函数
$field = new Input('name', 'My field');
$field->render()->with($field->data());
**数据函数包括组件的方法、属性和属性。您的类名是什么?该类在测试中称为“输入”无害,因此将您的laravel更新为7.9,您的代码如下所示:如果在标题前删除冒号该字段在刀片模板中呈现良好,我需要知道如何以编程方式呈现它。我正在创建一个系统,让用户创建自己的字段,我需要从代码而不是固定的模板呈现它们。