如何将Smarty变量赋值给JavaScript变量?附代码示例
Hey there! Let's clear up how to get this working right—your current code mixes up server-side (Smarty) and client-side (JavaScript) execution, which is why it's not behaving as expected. Let's break down the two common scenarios and their fixes:
Scenario 1: Pass a Smarty Variable's Value to a JavaScript Variable
Smarty runs on the server before the page ever reaches the browser, so we need to have Smarty output its variable's value directly into the JavaScript code. Here's how to do it safely:
Basic Example (Numbers/Booleans)
If your Smarty variable $cutValue is a number or boolean, you can output it directly:
<script type="text/javascript"> // First get your JS value from the plugin var jsCutValue = plgShirt.getValueCut(); // Assign Smarty's $cutValue to a JS variable var smartyCutValue = {$cutValue}; </script>
When the server renders the page, Smarty will replace {$cutValue} with its actual value—so if $cutValue is 15, the browser sees var smartyCutValue = 15;.
Safe Example (Strings)
For string values, always use Smarty's escape:'javascript' modifier to avoid syntax errors and XSS risks:
<script type="text/javascript"> var smartyCutValue = {$cutValue|escape:'javascript'}; </script>
This ensures quotes and special characters are properly escaped—so if $cutValue is "Hello World!", it becomes var smartyCutValue = "Hello World!";.
Scenario 2: Pass a JavaScript Variable's Value to a Smarty Variable
Wait a second—if your goal is to send the JavaScript cutValue back to Smarty (the server), you can't do this directly in the page. Smarty has already finished running by the time JavaScript executes in the browser. Instead, use AJAX to send the value to a backend script:
Step 1: JavaScript AJAX Call
<script type="text/javascript"> var cutValue = plgShirt.getValueCut(); // Send the value to your backend PHP script fetch('save_cut_value.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'cutValue=' + encodeURIComponent(cutValue) }) .then(response => response.text()) .then(data => { console.log('Value saved successfully!', data); // Optional: Refresh the page or update content to see the new Smarty value window.location.reload(); }) .catch(error => { console.error('Error saving value:', error); }); </script>
Step 2: Backend PHP Script (save_cut_value.php)
Save the value to a session so Smarty can access it later:
<?php session_start(); if (isset($_POST['cutValue'])) { $_SESSION['cutValue'] = $_POST['cutValue']; echo "Success"; } ?>
Step 3: Access the Value in Smarty
Now you can use the stored value in your Smarty template:
<p>Last saved cut value: {$smarty.session.cutValue}</p>
Key Takeaway
Always remember: Smarty runs first on the server, then JavaScript runs in the browser. You can't "assign" a JS variable to a Smarty variable directly in the page—you need to send data back to the server if you want Smarty to use it.
内容的提问来源于stack exchange,提问作者Tatiana Santillán

