【问题标题】:Tagged Blade component with variable name带有变量名称的标记刀片组件
【发布时间】:2020-08-18 12:55:49
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: laravel laravel-blade laravel-7


    【解决方案1】:

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

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

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

    希望对大家有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 2021-07-29
      • 2011-11-27
      • 2011-03-18
      • 2022-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多