Search code examples
javascriptvisual-studio-codejinja2

What is the correct way to put in Jinja code to JavaScript?


I am working on a Django project. The code can work and run perfectly fine, there is no issue at all.

But Visual Studio Code indicates this part of code as syntax errors. However, in Sublime Text, there are no syntax errors shown.

enter image description here

enter image description here

I would like to get rid of the syntax errors which VSCode reports. I don't want to see the syntax errors. What is the correct way to add Jinja code to JavaScript to get rid of the syntax error? I am thinking about making a separate file or something else. What would you suggest?


Solution

  • VS Code doesn't recognize the Jinja code written inside the <script> tag because you haven't installed the required extension and changed the settings.json file so that Visual Studio Code can recognize the Jinja code written inside the <script> tag.

    I also encountered a similar problem and this is what I did to fix it. This is a screenshot showing VS Code reporting syntax errors before I fixed the problem. This answer to a similar question gave me the clue.

    1. Install the Better Jinja extension (screenshot), which would enable keywords and identifiers in HTML Jinja templates to be highlighted.
    2. Click on the gear in the bottom left corner of the screen and select "Settings". In the "User" tab, find User >> Extensions >> Emmet and click on it (screenshot). Scroll down to "Preferences" and click on "Edit in settings.json".
    3. In the settings.json file (screenshot), paste the following code to replace the enmet.preferences:{} part:
    "emmet.preferences": {
            
        },
        "files.associations": {
            "*.html": "jinja-html"
        },
        "emmet.includeLanguages": {
            "jinja-html": "html",
        },
    }
    
    1. Check that the "Include Languages" setting under User >> Extensions >> Emmet and "Files:Associations" setting under User >> Text Editor >> Files have been modified. The item "jinja-html": "html" should have been added to the "Include Languages" setting and the item "*.html": "jinja-html" should have been added to the "Files: Associations" setting. Note that "*.embeddedhtml": "html" is the system default setting for "Files: Associations".
    2. Restart VS Code, and the syntax errors should be gone. My original code now looks like this. Your code should now look like this in VS Code.

    Syntax errors fixed

    Hopefully, you will find my answer helpful.