javascriptdjangodjango-templates

How to add Django template tags in a different Js file


Hi I want to add the tag {{request.user.first_name}} in my js code. I am aware that if the js code is within the HTML document you can easily add any Django template tag in Django version 3.2.

But for now, my HTML is as such...

<script src="{% static 'dashboard/driver.js' %}"></script>

Which contains over 2000 lines, and I do not want to include it in my HTML file.

So my question is can I add the tag {{request.user.first_name}} and several others in a separate JS file, in my case driver.js.

Any help would be greatly appreciated.

Thanks!


Solution

  • You can't add any Django template code in js file directly.

    There are 3 ways you can add the first_name in js file.

    1. Write a django ajax views and call the api for first_name from your js file as soon as your page is loaded. or
    2. render your first name in your html file hidden input fields and than grab the fields value it's name or id from your jsfile or
    3. put a utill function on your html js <sccript> tags which are gonna call you driver.js file related method.