如何通过HTML data属性将Blade语言数组注入脚本?
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 (eitheren/intro.phporde/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
@jsondirective 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

