我有一个刀片模板,其中包含一个脚本。 该脚本需要访问可通过@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 );更多推荐
发布评论