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

如何通过JSON实现Twig向Javascript传值?循环取值异常解决

Fix: Getting Only First Twig Loop Value in JavaScript

The root cause of your issue is duplicate IDs in your rendered HTML. When you use id="test" inside a Twig loop, every <div> gets the same ID—but IDs must be unique per page. That's why $('#test').data("isTest") always returns the first element's value, no matter how many times you loop.

Here's how to fix it, with clean, maintainable solutions:

Step 1: Update Your Twig Template

Instead of relying on a fixed ID, link each canvas to its specific data directly. You have two straightforward options:

Option 1: Attach Data Directly to the Canvas (Cleanest Approach)

Cut out the unnecessary inner div and attach the pts data straight to the canvas element. This keeps your HTML lean:

{% for i in score %}
    <canvas class="credsEarned" data-pts="{{ i.pts|json_encode }}"></canvas>
{% endfor %}

Option 2: Use a Class for the Inner Div (If You Need the Div)

If you must keep the inner div, replace the fixed ID with a reusable class so you can target it per canvas:

{% for i in score %}
    <canvas class="credsEarned">
        <div class="test-data" data-is-test="{{ i.pts|json_encode }}"></div>
    </canvas>
{% endfor %}

Step 2: Update Your JavaScript

Use jQuery's .each() method to iterate over every canvas, and pull the data specific to the current element (instead of grabbing a single fixed ID repeatedly).

For Option 1 (Data Attached to Canvas):

$(document).ready(function(){
    $('.credsEarned').each(function() {
        // Grab the unique data for this specific canvas
        var ptsData = $(this).data('pts');
        var context = this.getContext('2d');
        
        // Now you can use ptsData with your canvas context
        console.log('Points for this canvas:', ptsData);
        // Add your canvas drawing logic here using ptsData
    });
});

For Option 2 (Data on Inner Div):

$(document).ready(function(){
    $('.credsEarned').each(function() {
        // Find the inner data div within the current canvas
        var ptsData = $(this).find('.test-data').data('isTest');
        var context = this.getContext('2d');
        
        console.log('Points:', ptsData);
        // Your canvas rendering code goes here
    });
});

Why This Works

  • By linking data directly to each canvas (or using a class for the inner element), you ensure every loop iteration has its own unique pts value.
  • The .each() loop processes each canvas individually, so you'll pull the correct data for every item in your Twig score array—no more repeating the first value.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:16:01