0

I have been warned that this is subjective and likely to be closed, but seems an essential question that I haven't seen addressed.

I am currently coding webapps in Django and using a bit of JavaScript to do this and that. Naturally, I sometimes want to keep my JavaAcript apps from knowing the context of my Django template, so the way I've been doing it is hardcoding the JS into the .html file.

<script>
  var my_var = "{{ my_var_from_context }}"

Clearly this is ugly as all hell as it forces me to keep my JavaScript code inside of the .html file. I'd like to make my .js file separate and load it.

Clearly there are some options like writing a function that takes arguments that can be captured in the template then passed.

var my_var = "{{ my_django_var }}"
myFunctionFromScript(my_var)

Is this the best way to be doing this? Is there a better pattern? What are others doing?

Thanks for your help.

-Joe

normonics
  • 191
  • 1
  • 7
  • 1
    As I really don't want `js` code in my templates I usually put the parameters in custom data attributes of HTML objects. E.g. a delete button would have a `data-url` field that contains the url to the delete view. I can then read the value with jQuery. – Wombatz Nov 27 '17 at 18:22
  • What are you trying to pass as arguments to javascript? – Rajesh Yogeshwar Nov 28 '17 at 06:52
  • state and county names that become fips codes and then are passed on to the US Census API I want the js script to draw a widget on the page, but with properly contextualized data (state, county) – normonics Nov 28 '17 at 14:32

1 Answers1

1

With DTL (Django Template language) you can pretty much do any general purpose logical programming inside your HTML files.

I would suggest the approach below as there are less chances of django syntax messing up with the Javascript's object literal notation.

var my_var = "{{ my_django_var }}";
//do not forget double quotes above
myFunctionFromScript(my_var);

Also consider wrapping your code between {% verbatim %} and {% endverbatim %} tags to stop django interpreting any of your JS code in the templates.

Prakash Palnati
  • 3,231
  • 22
  • 35
  • Thanks for the comment. Yes I've been doing things similar to this but not totally satisfied witht the pattern. Just curious what others might do. Thanks, – normonics Nov 27 '17 at 18:24