You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HTML data属性将Blade语言数组注入脚本?

Solution: Inject Entire Language Array via Single Data Attribute

Absolutely! You can simplify this workflow by injecting the full intro language array as a JSON string into one data attribute, then parsing it in your script. This is way more scalable than adding individual attributes for each string—especially as your language set grows.

Step 1: Update Your Blade Template

Use Laravel’s @json directive to safely encode the entire language array into a single data-intro attribute. This directive automatically handles escaping to ensure the JSON is valid in HTML:

<script data-id="intro-script" data-intro='@json(trans("intro"))' src="{{ mix('js/intro.js') }}"></script>
  • trans("intro") pulls the full array from your active locale’s language file (either en/intro.php or de/intro.php).
  • @json() converts the array into a properly escaped JSON string, so it won’t break your HTML syntax or cause parsing errors later.

Step 2: Read the Data in Your Script

You can turn the JSON string into a usable JavaScript object with either vanilla JS or jQuery:

Vanilla JavaScript

// Grab the script element
const introScript = document.querySelector('script[data-id="intro-script"]');
// Parse the JSON data into a JavaScript object
const introStrings = JSON.parse(introScript.dataset.intro);

// Access individual language strings
console.log(introStrings.step1); // Outputs "Welcome" (en) or "Willkommen" (de)
console.log(introStrings.step2); // Outputs "Step 2" (en) or "Schritt 2" (de)

jQuery

jQuery’s .data() method automatically parses JSON-formatted data attributes into objects, so you skip the manual JSON.parse() step:

// Retrieve and parse the data in one go
const introStrings = $('script[data-id="intro-script"]').data('intro');

// Access your language strings directly
console.log(introStrings.step1);
console.log(introStrings.step2);

Why This Works

  • Scalability: Add new keys to your language file without touching the Blade template or script—they’ll automatically appear in the JSON object.
  • Safety: The @json directive escapes special characters (like quotes or HTML entities) to prevent syntax errors in both HTML and JavaScript.
  • Cleaner Code: Eliminates repetitive data attributes and keeps your template organized.

This is the standard, clean way to pass structured data from Laravel to JavaScript in Blade templates, and it works perfectly for language arrays of any size.

内容的提问来源于stack exchange,提问作者ffritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:54:31