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

Django:使用JavaScript变量访问Django上下文数组

Fixing Dynamic Access to Django Context Data in JavaScript

Hey there! I’ve run into this exact gotcha before when mixing Django templates and JavaScript—let’s break down why your approach isn’t working and walk through the best fixes.

Why Your Current Code Fails

Django’s template rendering happens on the server before the page even reaches your browser. When the server tries to process {{ users." + i + ".name }}, the JavaScript variable i doesn’t exist yet (it only gets created once the browser runs your JS). The server can’t resolve that dynamic index, so your alert ends up showing broken template syntax instead of the user’s name.

The cleanest, most flexible way is to serialize your users array into a JSON string on the server, then parse it into a proper JS array in the client. Here’s how:

Step 1: Safely Embed the JSON in Your Template

Use Django’s json_script filter to avoid XSS risks and handle escaping automatically:

<!-- In your Django template -->
{{ users|json_script:"users-data" }}

Step 2: Access the Data in JavaScript

Now parse the serialized JSON into a JS array and use your dynamic index i:

var i = 1;
// Turn the serialized data into a usable JavaScript array
const users = JSON.parse(document.getElementById('users-data').textContent);
// Now you can access it like any regular JS array!
alert(users[i].name);

Quick Alternative (For Simple, Trusted Data)

If you’re sure your users data doesn’t contain special characters or untrusted content, you can directly assign it to a JS variable with the safe filter:

var i = 1;
// Convert Django's users array to a JS array
const users = {{ users|safe }};
alert(users[i].name);

Stick with json_script for production, though—it’s safer for most cases.

Solution 2: Store Data in DOM Attributes (For UI-Tied Use Cases)

If you only need user data linked to specific DOM elements, embed the info directly in data-* attributes:

<!-- In your Django template, loop through users to create elements -->
{% for user in users %}
<div class="user-card" data-user-name="{{ user.name }}"></div>
{% endfor %}

Then grab the element by index and access the data in JS:

var i = 1;
// Get the i-th user element (adjust the selector to match your HTML)
const userElement = document.querySelectorAll('.user-card')[i];
// Pull the name from the data attribute
alert(userElement.dataset.userName);

This works great if your user data is tied to UI components, but it’s less flexible than having a full JS array.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:44:52