Pass data to javascript file #399
-
Is there a way to pass template context data to the javascript file? usecase: I want to use a unique ID attribute for an html element and I want to query said element in the javascript file. template <div id="{{unique_id}}">...</div> javascript // I'm assuming the varialbe is passed along through 'data' attributes
const data = document.currentScript.dataset;
const unique_id = data.unique_id;
const element = document.querySelector(unique_id); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
Hi @franciscobmacedo! Great question. I'm thinking we should maybe create a unique ID for each instance of a component automatically and make that easy accessible. But for now, I think you could override render_js_dependencies and just replace |
Beta Was this translation helpful? Give feedback.
-
Not an answer to this question directly, but want to throw it out there. In my project we use AlpineJS, and I structure django components to have (mostly) the same boundaries as AlpineJS components. And it works fairly well, because AlpineJS is in charge of ensuring that each AlpineJS component has its own JS context and is initialized when the component is rendered in the browser. And to pass different data for different component instances, I pass the data from Django to HTML (as dataset), and then from within AlpineJS I query the HTML element for the data. AlpineJS also handles the case of generating unique IDs for their components on the spot. See https://alpinejs.dev/magics/id |
Beta Was this translation helpful? Give feedback.
Oh wait. If you specify your javascript as a dependency it will just be rendered once, which kind of defeats the purpose. I guess you could put the script tag in the template file?