Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Pass the value from your Django view into the rendered template, serialize it with Django’s json_script filter, and read that JSON from your external JavaScript file. Django does not render template variables inside an ordinary static .js file. If the browser should retrieve data separately or refresh it on demand, expose a JSON endpoint instead.

Why a Django variable is unavailable in an external JavaScript file

Django template variables are evaluated while Django renders a template for a request. A static JavaScript file is served as an asset; it does not pass through that per-request template-rendering step. Writing const value = "{{ value }}"; in a regular external .js file therefore will not insert the view’s context value.

Instead, put the data in the rendered HTML for the page to load, or have JavaScript request it from a Django endpoint. Django’s static files guide covers serving assets separately from templates, while its template documentation explains the view-and-template rendering process.

Pass page data with Django’s json_script filter

For structured data needed as soon as the page loads, use json_script. It writes a Python object as JSON into a non-executable <script type="application/json"> element. Your external JavaScript can read the element’s text and parse it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

1. Add the value to the view context

Prepare the value in the view and include it in the context passed to the template. This example uses a dictionary, but json_script can serialize JSON-compatible Python data.

from django.shortcuts import render

def home(request):
    page_data = {
        "message": "Hello from Django",
        "items": ["one", "two"],
    }
    return render(request, "home.html", {"page_data": page_data})

2. Add the JSON data and external file to the template

In home.html, render the value with an ID that your JavaScript will use. Load Django’s static template tag before using it to build the JavaScript asset URL.

{% load static %}

{{ page_data|json_script:"page-data" }}
<script src="{% static 'my_app/app.js' %}" defer></script>

Replace my_app/app.js with the path to your file under the project’s static files. The view must pass a context value named page_data, as in the example. For several independent values, give each JSON element a distinct ID.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

3. Read and parse the value in the external JavaScript

In app.js, select the matching ID and parse its textContent:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const dataElement = document.getElementById("page-data");
const pageData = JSON.parse(dataElement.textContent);

console.log(pageData.message);

The defer attribute makes the browser run the external script after parsing the document, so the JSON element is available when the code runs. Keep the ID in the template and the JavaScript selector identical.

Django’s json_script documentation specifies that the filter escapes <, >, and & in its output. It also supports a strict Content Security Policy that prohibits in-page script execution because the element holds passive data, not executable JavaScript.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Use a JSON endpoint for data fetched separately

Choose an endpoint when the data is large, is needed only after a user action, or changes independently of the initial page. The browser makes a request, so the data can be loaded on demand or requested again when needed.

Create a Django view that returns JSON

JsonResponse returns JSON with an application/json content type by default and expects a dictionary as its first argument:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from django.http import JsonResponse

def page_data(request):
    return JsonResponse({"message": "Hello from Django"})

Fetch and parse the response

Call the endpoint from your external JavaScript. Check the response status before parsing the body so failures do not look like successful data loads.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
const response = await fetch("/page-data/");
if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}
const data = await response.json();

Replace /page-data/ with the URL pattern for your view. For a JSON response whose top-level value is not a dictionary, Django allows JsonResponse(data, safe=False); its documentation notes that dictionary-based APIs are generally more extensible and maintainable. See Django’s JsonResponse documentation.

Choose the method that matches when the data is needed

Need Use What happens
Small data required as soon as the rendered page loads json_script The JSON is included in the HTML response, so the external file can read it without a separate request.
Large, on-demand, or independently refreshed data JSON endpoint The browser makes a separate request and receives a JSON response.

These are practical trade-offs, not a Django rule that one approach must always be used. Use the endpoint when a separate request boundary is useful; use json_script for initial page data.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep the data safe when passing it to JavaScript

Prefer json_script to interpolating a value into executable JavaScript. HTML escaping is not a guarantee that arbitrary output is safe in every JavaScript context. Avoid disabling escaping with Django’s safe filter or mark_safe for untrusted values, and validate user-controlled input for its intended use. Django’s security guidance states: “The golden rule of web application security is to never trust user-controlled data.” OWASP’s Cross Site Scripting Prevention Cheat Sheet also recommends json_script for passing data to JavaScript and cautions against disabling automatic escaping.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

JSON encoding does not make a value safe for every later use. If you display a value as plain text, use a DOM API such as textContent; do not build executable markup from untrusted strings.

Load the external file correctly in development and production

Use Django’s {% static %} template tag to generate the external file’s URL. In development, Django’s runserver can serve static files when django.contrib.staticfiles is installed and DEBUG=True. Django says this development method is unsuitable for production. In production, collect static assets as appropriate and serve them using your deployment’s static-file strategy, such as a web server or CDN. Follow the static files guide for the Django version used by your project.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.