While creating several html templates in Python Django web application in Visual Studio Code, It will be a good practice to create a code snippet instead of copy paste the template code in several files. Snippet technique gives a consistent source of code from a single place. This avoids several problems and errors caused because of copy-paste. Here we will see how to create a code snippet and using it to create templates.
For example, Let’s consider that you are using a base template (named layout.html, which has the common content like the navigation bar) in your project and refer this base template url in other page templates. In further page templates, you have to at least use the below template code to start with. (Refer my previous article for creating templates)
{% extends "dj_app/layout.html" %}
{% block title %}
{% endblock %}
{% block content %}
{% endblock %}
Instead of copy-pasting the above code in every new template page, you can use the Visual Studio Code’s code snippet option. Let’s see how to create a code snippet and use it.
Creating code snippet
- In VS Code, from the menu go to File (in Windoes or Linux) or Code (in macOS), then go to Preferences… >> User snippets.
- From the list select html.json (HTML).
- The file html.json will open up in the editor.
- In the file, below the commented text and above the closing curly braces, add the below code.
"Django Web App: Template extending base template": {
"prefix": "pydjlayout",
"body": [
"{% extends \"dj_app/layout.html\" %}",
"{% block title %}",
"$0",
"{% endblock %}",
"{% block content %}",
"{% endblock %}"
],
"description": "Page template that extends the base template - layout.html"
},
- The snippet has four sections.
- Snippet name: The first line is the snippet’s name.
- Prefix: One or more words which display the snippet in IntelliSense.
- Body: Has the template code. In this example, I’ve added “$0” in between the title block, so as the cursor will be positioned accordingly.
- Description: This is optional. This will be displayed in the IntelliSense.
- Finally save the snippet file
Using code snippet
Let’s see how to use this snippet in the templates.
- Create a html file (probably in the template folder in your web app).
- Start typing in the prefix of the snippet pydjlayout to see the description of the snippet as completion.
- Select the completion. The template code will be added to the file.
- You can see the cursor will be in the position where we have added “$0” in the snippet. Use can use this snippet to any number of page templates where you need to refer the base template.
Reference
- About web development in Python with Django using VS Code at VS Code Docs.