Javascript is not recognizing a Flask variable - javascript

I'm passing a set of variables into a Flask template, and I would like to first manipulate them with Javascript. The problem is that when I use the {{ var }} syntax, Javascript isn't recognizing it.
The errors look like this. The left brackets give an "Identifier or string literal or numeric literal expected" error, and the variable names give an "Expression statement is not assignment or call" error.
I use {{ var }} syntax later, within the HTML portion of the document, and when I do that they appear just fine. Also, enclosing it in quotes as I do for a different variable doesn't work either. Anyone know what the issue could be? Thanks.

Jinja2 (flask's templating engine) is a preprocessor, meaning that its output is the real JS and it does not care about you're using it with HTML, JS or whatever, it only prints text.
That error you're getting is your text editor trying to help you but it's not smart enough to realize you're writing Jinja2 instead of javascript.
Edit: also, as #davidism says, you have to use jinja2 blocks.

Related

How to get jsdoc to work with django template tags?

I have js files with {% %} template tags in them, which causes jsdoc to fail with
ERROR: Unable to parse <path>: Unexpected token
Is there any way to get django template tags to work with jsdoc or any other javascript doc generator?
Mixing the javascript and django's template language is inherently bad, try to avoid that. In the case of jsdoc I think that you need to look into its interpolation which would be fairly complex task.
The other solution that I can think of is to switch the dafault django template language with jinja2. And then you can set there something like these: https://gist.github.com/lost-theory/3925738 but you might encounter an error again.
What I would do is this, put constants in the place of the variables and then generate the docs, after that simply put back the django's variables.

Ignore javascript error in HTML file (VS Code)

I have an HTML file which is a Django template. For the most part, it's pretty boring, there's a bit of HTML and some Javascript code inside script tags.
The problem is that I've inserted a single line of Django template language (with the double curly braces), and it cascades into a thousand different errors on every line. How do I ignore this? All I can find is // #ts-ignore on Google which doesn't seem to work with HTML files.
I don't even know where to begin. Is this a linting issue? What linter am I using, which documentation should I look at, etc. I assume I should be using the default tools for javascript. Please help!
The line in question is:
var achievementFlag = {{ achievement_flag|yesno:"true,false" }};
Naturally, the double curly braces is bad, as is the | and the :. And now the javascript just has squiggles all over it.
Add this line to settings.json
"html.validate.scripts": false,
this line will make vscode ignores javascript validation in HTML files
credits: https://github.com/Microsoft/vscode/issues/17433#issuecomment-273870328

Escaping quotes in Angular with Freemarker Templates

In a Freemarker template on a page with Angular, I have the following:
...
ng-init="somevariable = ${(model.usercontrolledstring)}"
...
I want to make sure this is hardened against XSS, so I've set up some escaping rules. However, the following value for model.usercontrolledstring causes JavaScript to execute:
abc'+constructor.constructor('alert(1)')()+'abc
The surprising thing is that when the client receives it, it arrives thusly:
ng-init="somevariable = 'abc'+constructor.constructor('alert(1)')()+'abc'"
So it looks like it's being escaped correctly, but Angular is still deciding to run it!
So I guess my questions would be:
What am I not understanding about Angular? (In particular, its decision to run after decoding html entities)
Is there a proper way of configuring a Freemarker Template to prevent this sort of XSS?
I believe you should use somevariable = '${model.usercontrolledstring?jsString}' there.
Also, if that thing goes into a <script> block, certainly you shouldn't apply HTML escaping there. It's not decoded by the browser inside <script>, so you end up with string values that literally contain '. Unless the string meant to contain HTML as opposed to plain text, that's wrong.

Javascript Uncaught Syntax error caused due to passing of variable

I am trying to pass a few variables from my php to the javascript and its working fine except for when I add a particular variable to the function call. There are 3 variables being passed all of which are related to a youtube video. the ID is being retrieved from a database, and the other two (title and description) are being retrieved using the ID from the youtube api.
<a href="#" class="list-group-item" id="{{$vidID[$i]}}" onclick="updateVid('{{$vidID[$i]}}', '{{$title[$i]}}', '{{$desc[$i]}}test')">
I am using hogan templating so the {{}} is the same as php tags with an echo. The problem only seems to occur when I add in the description variable to the call. Without it, the other two work perfectly fine. After doing some research it seems this is caused by an invisible character but I retyped my code to make sure and my code wasn't the problem. The developer console shows that problem is occurring on the last line of the description variable so it seems that the description is being retrieved with an invisible character from the api. I am just trying to do a simple alert with the description in the js function. How can I get rid of this character?
Without seeing the actual values, the most obvious problem would be that characters in your content are breaking the html and / or the javascript function call.
Echoing variables directly in html like that is a bit tricky as you need to escape for the javascript but also for the html. In this case you can probably use:
... '{{htmlspecialchars(json_encode($desc[$i]), ENT_QUOTES)}}test' ...
The json_encode call will probably get you an extra pair of double quotes around the string.
However, note that the best way to get your variables to javascript is to do that directly in a script block - without html in the middle - using json_encode in php. Then you can be sure any data can be passed without problems and you can decode it in javascript to get your structure back (in case of arrays and objects).

What is the # symbol in Javascript?

I stumbled upon https://codereview.stackexchange.com/questions/10610/refactoring-javascript-into-pure-functions-to-make-code-more-readable-and-mainta and I don't understand the answer since the user uses an # symbol in a way I've never seen before. What does it do when attached to the if keyword? Can you attach it to other keywords?
It's not a JavaScript thing. It's a symbol used by whatever templating system that answer was referring to. Note that the <script> element has type text/html, which will prevent browsers from paying any attention to its contents.
Some other JavaScript code will find that script and fetch its innerHTML in order to merge the template with some data to create ... well whatever that template makes.
#: syntax in Razor
Said by #StriplingWarrior at Using Razor within JavaScript
It is razor code, not javascript, if you are interested in razor check:
http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx

Categories