[Fixed]-How to pass a django variable from html page to javascript

1👍

I can’t find the reference, but I’m skeptical <script src="something.js"> can also have source within it. I’ve not seen it done that I can recall.

This should work, which is similar to what you are doing:

<script>
    var user = '{{request.user.get_full_name}}'; // created by your django html 
</script>
<script src="{% static 'app/js/sidebar.js' %}"></script>

And then in your sidebar.js you just need to do:

"....<h3>" + user + "<h3>..."

However, a cleaner way to do this would be to encapsulate your js into a function that takes the username as a parameter:

<script src="{% static 'app/js/sidebar.js' %}"></script>

Where your js is something like,

function sidebar(user) {
    document.getElementById("navMenu").innerHTML = "....<h3>" + user + ";<h3>..."
}

Followed by:

<script>
    sidebar('{{request.user.get_full_name}}'); // where this is created via your template.
</script>

Leave a comment