laravel - 带有变量名称的标记刀片组件
问题描述
我有一个视图,应该根据存储名称的变量的值来呈现不同的标记组件。例如
@if( $a['type'] == 'component' )
"<x-{$a['name']} />"
@endif
但是我找不到正确的方法,因为使用刹车{{ }}
也会将它们打印在页面上(组件之前和之后)。
组件类也有一些被调用的函数,所以该@component
指令只能解决部分问题。
解决方案
我可能已经找到了解决方案,我会在这里发布以供参考。它目前有效,但我不能说它以后不会给我带来麻烦,如果你找到更好的方法,我很乐意看看。
在像往常一样创建了一些刀片组件之后
php artisan make:component MyComponent1
php artisan make:component MyComponent2
php artisan make:component MyComponent3
并声明了所有需要的属性和方法,您可以以常规方式将组件包含在视图中
<html>
<head></head>
<body>
@if($somethingHappens)
<x-my-component1 a="" b="" :c="$c" class="" />
@elseif ($somethingElseHappens)
<x-my-component2 a="" b="" :c="$c" class="" />
@else
<x-my-component3 a="" b="" :c="$c" class="" />
@endif
</body>
</html>
或者,如果您希望更灵活地决定在运行时应该使用哪个组件并在视图之外的其他地方生成组件标签,我找到了这个解决方案
//some code.....
return('myview')->with([
'type' => 'component',
'component' => '<x-my-component3 a="" b="" :c="$vars[\'c\']" class="" />',
'vars' => [ 'c' => 'somevalue' ]
]);
#################
//myview.blade.php
<html>
<head></head
<body>
@php
if($type == 'component')
echo compileStringComponent(
$component,
$__env,
$vars
);
@endphp
</body>
</html>
################
//file containing the function
use Illuminate\View\Factory as ViewFactory;
//This function takes the whole tagged component as string and returns the corresponding html
function compileStringComponent(string $component, ViewFactory $__env, $vars = null )
{
$compiled = Blade::compileString($component);
ob_start();
try {
eval('?>'.$compiled);
} catch (\Exception $e){
ob_get_clean();
throw( $e);
}
$content = ob_get_clean();
return $content;
}
几点注意事项:
1) Blade::compileString 返回一个编译后的字符串以进行评估,并且在代码内部有一些对 $__env 变量的引用,它是 Illuminate\View\Factory 的一个实例,并且已经存在于视图中。这意味着如果在视图之外调用函数,则必须将 $__env 变量传递给调用者
2) 如果数据通过 :attributes 传递给组件,则需要 $vars 数组,原因与上述相同,因为这些变量不会存在于调用者内部,必须传递给它
3) ob_start() 和 ob_get_clean() 用于避免在出现任何错误时向用户发送不完整的视图。
我希望它会帮助某人
推荐阅读
- java - namenode 无法在 ambari 中启动
- nutch - 确保 Nutch 已爬取特定域的所有页面
- php - 在 IndexController.php 中执行 CLI 命令的问题
- sql - 从 MDX 查询 SSAS 返回两个日期之间的数据
- xpath - 如果在单个报告中使用两个 XPath 表达式,如何修复“未找到字段”错误?
- javascript - 我正在尝试使用 .push() 保存多个值,但我得到了 '{}'
- php - 如何在输入日期html中设置今天的日期
- angular - 如果库导入另一个启用了常春藤的库,Angular 9 无法在启用了常春藤的库上运行故事书
- javascript - 如何监视(使用 Jest)酶中的子组件方法?
- django - 是否建议在 Google Cloud Platform 上为新的 Django 项目安装和配置 UFW?