Sure. Everything that is in the template between the directives {% if ... %} and { % end %} is sent only to the browser if the if expression is True. So, anything there, whether it be a <script > with embedded javascript or a <link> tag importing a javascript file from somewhere, will only be transmitted over the network in this case.
You can even place an if or for directive inside the Javascript code itself to enable or disable portions of the code based on conditions known to the server code. This, not to mention embedding or not the whole part of the code, I believe that this will not be considered a good assessment - because it will confuse the server and client sides of your code in undesirable ways.
To access a variable from javascript, simply do:
var enabled = {{enabled}};
The value inside the token {{...}} displayed using a server variable.
In this case, to ensure compatibility of the values โโin enabled in Python and Javascript, you should use the number 0 for False and 1 for True (because if you use Boolean Python, the template will display as var enabled = True; - this is not something javascript would expect, since the reserved "true" in Javascript was lowercase)
The only limitation is that you can only set server variables before the page is sent to the browser. Therefore, if you need to set any variable on the server side, which depends on the user's actions on the displayed page, this way of doing things will no longer cut out (only when the page is reloaded). the way to make the page interdependently updated without reloading is to rely on asynchronous communications from javascript (previously known exclusively as "ajax").
edit - OP further asked:
here is the problem: when I return a string variable such as myvar = 'foo-bar' to the template, and when this {{myvar}} gets evaluated in the JS code, JS seems to interpret foo-bar as a variable name instead of a string. In this case, it will cause an error, because - means subtraction. How to make JS recognize foo-bar as a string value?
Again, what happens is pretty simple: the template operator {{ <expr> }} inserts the string representation of the rsulting expression - so if you have python myvar = "bla" and in the var myvar = {{ myvar }} template that gets visualization (and sent to the clientโs browser this way) like var myvar = bla - without the quotes around bla - thatโs why javascript treats it as a variable name. Workarounds for this include extra quotation marks around your variable if it is a string, either on the Python side or on the template.
In the template, you can: var myvar="{{ myvar }}" - or, on the Python side, when defining myvar: myvar = '"%s"' % "bla"