1

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!

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

No you can't but the solution is very simple. In your html just above where you have your linked script, add a script element that gets the variables you need using django template tags, e.g.

<script>
    var var1 = {{ var1 }};
    var var2 = {{ var2 }};
    var var3 = '{{ var3 }}';
</script>

Then you can just use var1, var2, var3 etc in your static script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.