简体   繁体   English

@include Laravel Blade 模板使用 Javascript 附加

[英]@include Laravel Blade Template to append using Javascript

I'm trying to reuse the same HTML code in both PHP and Javascript.我正在尝试在 PHP 和 Javascript 中重用相同的 HTML 代码。 In PHP I'm using Laravel's component mechanism to load the file passing the necessary parameters.在 PHP 中,我使用 Laravel 的组件机制来加载传递必要参数的文件。

@foreach($files as $file)
    <x-my-file name="my_name[][image]" imageId="{{ $file->id }}" imageUrl="{{ $file->url }}" />
@endforeach

It's working just fine.它工作得很好。

At the bottom of the page, I'm using jQuery like below:在页面底部,我正在使用 jQuery,如下所示:

@push('scripts')
    <script>
        var imageId = null;
        var imageUrl = '';
        jQuery(function($) {
            $('body').on('click', '#btn-add', function() {
                var imageId    = $(this).data('id');
                var imageUrl   = $(this).data('url');

                $('#target').append(`@include('components.my-file', ['name' => 'my_name[][image]', 'imageId' => 15, 'imageUrl' => '/path/to/an-image.jpg'])`);
            });
        });
    </script>
@endpush

Everything just works fine.一切正常。 With every click, the same component is getting appended with the same data that I've passed.每次单击时,同一个组件都会附加我传递的相同数据。

But, if I replace the static values of the following line:但是,如果我替换以下行的静态值:

$('#target').append(`@include('components.my-file', ['name' => 'my_name[][image]', 'imageId' => 15, 'imageUrl' => '/path/to/an-image.jpg'])`);

with the dynamic values I have, using the Javascript template literals:使用我拥有的动态值,使用 Javascript 模板文字:

$('#target').append(`@include('components.my-file', ['name' => 'my_name[][image]', 'imageId' => ${imageId}, 'imageUrl' => ${imageUrl}])`);

The page stopped rendering with a Parse error from Laravel:页面因 Laravel 的解析错误而停止渲染:

ErrorException错误异常
Use of undefined constant imageId - assumed 'imageId' (this will throw an Error in a future version of PHP)使用未定义的常量 imageId - 假定为“imageId”(这将在 PHP 的未来版本中引发错误)

Alternative?选择?

I've seen some AJAX methods on loading blade in Javascript that I personally did not like.我已经看到了一些我个人不喜欢在 Javascript 中加载刀片的AJAX 方法

Debugging调试

If I comment out the line, it still throws the same error until I remove the line completely.如果我注释掉该行,它仍然会抛出相同的错误,直到我完全删除该行。 Hence I'm suspecting that the curly braces of the JS template literals ( ${} ) are getting parsed as a Laravel blade syntax ( {{}} ).因此,我怀疑 JS 模板文字( ${} )的花括号被解析为 Laravel 刀片语法( {{}} )。

Please note that instead of the backticks ( ` ) I tried with the single quote and double quotes ( as can be seen here ), but getting errors as they are conflicting with the HTML code.请注意,我尝试使用单引号和双引号(如此处所示)代替反引号 ( ` ),但由于它们与 HTML 代码冲突,因此出现错误。

I've gone through the Laravel Documentation on Blade and JS Frameworks , but IMO, both the @ syntax and @verbatim are for the exact opposite purpose, and won't serve me.我已经阅读了关于Blade 和 JS Frameworks的 Laravel 文档,但是 IMO, @语法和@verbatim都用于完全相反的目的,不会为我服务。

Update更新

I eventually came up with an alternative to have blade in JavaScript:我最终想出了在 JavaScript 中使用 Blade的替代方法

@push('scripts')
    <script type="text/template" id="my-template">
        @include('components.my-file', ['name' => 'my_name[][image]'])
    </script>
    <script>
        var template = document.getElementById('my-template').innerHTML;
        console.log(template); // Successful grabbing the HTML.

        $(template).find('.image-placeholder').attr('src', imageUrl); // Replaced the HTML with the modified img tag only.
        console.log(template.prop('outerHTML'));
    </script>
@endpush

With this code, I can have the HTML perfectly without the dynamic data.使用此代码,我可以在没有动态数据的情况下完美地获得 HTML。 The first console.log is showing the HTML perfectly:第一个console.log完美地显示了 HTML:

<div>
    <img src="" alt="" class="image-placeholder">
    <input type="hidden" name="my_name[][image]" value="">
</div>

Now, the template is not a Laravel blade/component so far, so I have to put my dynamic data onto it.现在,模板到目前为止还不是 Laravel 刀片/组件,所以我必须将我的动态数据放在上面。 When I'm trying to put my dynamic data onto the HTML, the HTML is being replaced by the modified <img> string completely.当我尝试将动态数据放入 HTML 时,HTML 将完全被修改后的<img>字符串替换。 The second console.log output is:第二个console.log输出是:

<img src="/dynamic-path/to/the-image.jpg" alt="" class="image-placeholder">

Blade components are served by laravel. Blade 组件由 laravel 提供。

After response returned from server blade component won't work anymore.从服务器刀片组件返回的响应将不再起作用。

You can use some kind of placeholder and replace them dynamically as you did last time.您可以使用某种占位符并像上次一样动态替换它们。

As example,例如,

 var template = document.getElementById('my-template').innerHTML; template = template .replace('{src}', 'https://example.com/image.jpg') .replace('{id}', 'ImageID') .replace('{name}', 'my_name[][image]') console.log(template)
 <!-- <script type="text/template" id="my-template"> <x-my-file name="{name}" imageId="{id}" imageUrl="{src}" /> </script> I am using a template below --> <script type="text/template" id="my-template"> <div> <img src="{src}" id="{id}" class="image-placeholder"> <input type="hidden" name="{name}" value=""> </div> </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM