7

A similar question like this: Javascript is not recognizing a Flask variable

When I type things like this in vscode,

<script type="text/javascript">
    var x ={{ data }};
</script>

it will always reformat like this

<script type="text/javascript">
    var x = {
        {
            data
        }
    };
</script>

No longer a Jinja variable, and cannot really work in js.
So, is there such a plugin in vscode that can fix this problem?

funkid
  • 577
  • 1
  • 10
  • 30
  • not tested, so not sure, but: https://github.com/wholroyd/vscode-jinja – Nsevens Nov 21 '18 at 13:32
  • Thanks, but it doesn't help. Is it a possible way to try something on type="text/javascript"? Like change the – funkid Nov 21 '18 at 13:41
  • I think, for one way to get around this, you can put that `{{ data }}` variable into a string `"{{ data }}"` and then, if needed, parse it. Once it's in quotations, VSCode won't change it. – AJC24 Nov 21 '18 at 14:20
  • Thanks, that's a nice try, but there is still a problem: it cast the variable into string type. – funkid Nov 21 '18 at 14:35
  • As I said in my previous comment, if it's a number you are looking to store as the variable you need to do something like `parseInt("{{ data }}");` to convert it from a string to a number. You must parse it to the data type that you want to use. – AJC24 Nov 21 '18 at 20:01
  • Thanks! I find [a great way](https://stackoverflow.com/questions/37259740/passing-variables-from-flask-to-javascript?noredirect=1&lq=1) to solve this problem which inspired by your advice on `parse`. – funkid Nov 22 '18 at 01:54

1 Answers1

2

The problem here lies with VSCode, especially with Syntax Highlighting and Formatting Extensions.

There is some conflict between some of your enabled extensions which - on save - format the JavaScript code in above way.

  1. Disable all enabled formatting extensions in VSCode

  2. I only activated the following:

    • Python
    • Python Extension Pack by Jayamanne
    • Better Jinja by Samuel Colvin

This way on save the syntax doesn't get shredded anymore making the JavaScript recognize your {{ data }} correctly.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Deluroth
  • 53
  • 1
  • 7
  • This sort of works for me. However, there are more dependencies that get added that seem to be required to avoid the error flags. With all that installed the errors don't get flagged which is perfect. My one setback is the commenting shortcut is a little funky - for example, I get `{% comment %}

    SomeHeading

    {% endcomment %}`. I'm using mac Venture, in case that matters. Curious if anyone ideas?
    – costa rica Jul 06 '23 at 11:43