使用HTML数据属性将刀片阵列注入脚本(Inject Blade Array into script using HTML data attribute)

编程入门 行业动态 更新时间:2024-10-26 21:28:25
使用HTML数据属性将刀片阵列注入脚本(Inject Blade Array into script using HTML data attribute)

我有一个刀片模板,其中包含一个脚本。 该脚本需要访问可通过@lang('intro')变量访问的语言字符串。 我想知道是否有方法通过html数据属性将整个数组注入脚本,然后使用jquery在脚本中检索它。

到目前为止,我有以下几点:

../en/intro.php:

<?php return [ 'step1' => 'Welcome', 'step2' => 'Step 2', ];

../de/intro.php

<?php return [ 'step1' => 'Willkommen', 'step2' => 'Schritt 2', ];

在刀片模板中,我正在注入每个字符串:

<script data-id="intro-script" data-introStep1="@lang('intro.step1')" data-introStep2="@lang('intro.step2')" src="{{ mix('js/intro.js') }}">

并在脚本intro.js使用jQuery检索它:

document.querySelector('script[data-id="intro-script"]').getAttribute('data-introStep1');

这工作到目前为止,但不是很多更多的字符串。 我想知道是否有可能将data-introStep1和data-introStep2到包含整个@lang('intro')数组的单个数据属性中,而不仅仅是每个属性的单个字符串。

I have a blade template, which has a script included in it. That script needs access to language strings, which are accessible in a @lang('intro') variable. I am wondering if there is way of injecting the whole array into the script via a html data attribute, and then retrieve it in the script using jquery.

So far I have the following:

../en/intro.php:

<?php return [ 'step1' => 'Welcome', 'step2' => 'Step 2', ];

../de/intro.php

<?php return [ 'step1' => 'Willkommen', 'step2' => 'Schritt 2', ];

In the blade template I am injecting each string:

<script data-id="intro-script" data-introStep1="@lang('intro.step1')" data-introStep2="@lang('intro.step2')" src="{{ mix('js/intro.js') }}">

And retrieve it using jQuery in the script intro.js:

document.querySelector('script[data-id="intro-script"]').getAttribute('data-introStep1');

This works so far, but isn't great for many more strings. I am wondering if its possible to combine data-introStep1 and data-introStep2 in a single data attribute which contains the whole @lang('intro') array, not just a single string per attribute.

最满意答案

您的翻译文件可以打包成JSON编码的字符串,如下所示:

<script data-id="intro-script" data-intro='@json(__('intro'))' src="{{ mix('js/intro.js') }}" ></script>

然后,使用Javascript进行检索。

const intro = JSON.parse( document.querySelector('script[data-id="intro-script"]').dataset.intro );

Your translation file can be packed as JSON encoded string like so:

<script data-id="intro-script" data-intro='@json(__('intro'))' src="{{ mix('js/intro.js') }}" ></script>

Then, retrieve using Javascript.

const intro = JSON.parse( document.querySelector('script[data-id="intro-script"]').dataset.intro );

更多推荐

本文发布于:2023-07-20 02:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1192062.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阵列   刀片   脚本   属性   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!