首页 > 解决方案 > 带有变量名称的标记刀片组件

问题描述

我有一个视图,应该根据存储名称的变量的值来呈现不同的标记组件。例如

@if( $a['type'] == 'component' )
    "<x-{$a['name']} />"
@endif

但是我找不到正确的方法,因为使用刹车{{ }}也会将它们打印在页面上(组件之前和之后)。

组件类也有一些被调用的函数,所以该@component指令只能解决部分问题。

标签: laravellaravel-bladelaravel-7

解决方案


我可能已经找到了解决方案,我会在这里发布以供参考。它目前有效,但我不能说它以后不会给我带来麻烦,如果你找到更好的方法,我很乐意看看。

在像往常一样创建了一些刀片组件之后

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() 用于避免在出现任何错误时向用户发送不完整的视图。

我希望它会帮助某人


推荐阅读