DEV Community

Cover image for Code Like a Pro: How to use templates in IntelliJ IDEA & VS Code
cuongnp
cuongnp

Posted on • Updated on

Code Like a Pro: How to use templates in IntelliJ IDEA & VS Code

One of my favorite things before diving into coding with IntelliJ IDEA and Visual Studio Code is setting up templates. This step can significantly enhance productivity and contribute to cleaner, more organized code files.

Using templates offers a range of benefits, but personally, I find them invaluable for quickly generating header files and creating shortcuts for common code patterns. Now, let's explore how to set up and utilize these templates effectively!

Create file header

IntelliJ IDEA ( Android Studio)

  • There are 2 ways to create header file in IntelliJ

Auto generate header when create a new file

Auto generate

  1. Open IntelliJ IDEA.
  2. Go to IntelliJ IDEA > Settings (or IntelliJ IDEA > Preferences on macOS) to open the Settings window.
  3. In the Settings window, navigate to Editor > File and Code Templates.
  4. Select Includes tab > File Header
  5. Create your own template

    /**
     * ${NAME}
     *
     * @author Your Name
     * Date: ${DATE} 
     * Time: ${TIME}
     */
    
  6. Apply and OK

Auto generate

Manually create header file with Live Template

Manually template setting

  • To create a live template in IntelliJ IDEA for documentation such as author, date time, and description for code files, you can follow these steps:
  1. Open IntelliJ IDEA.
  2. Go to IntelliJ IDEA > Settings (or IntelliJ IDEA > Preferences on macOS) to open the Settings window.
  3. In the Settings window, navigate to Editor > Live Templates.
  4. Click the + button to add a new live template.
  5. Enter an abbreviation for your template, for example, **fileheader**.
  6. Below the Template text area, you can define variables like author, date, time, etc. Click the Edit variables button.
  • Don't forget to change to apply for EveryWhere

    /** 
    * Description: $description$ 
    * Author: Your Name 
    * Date: $date$ 
    * Time: $time$
    */
    

Result

> For each variable, specify its name, expression, and default value. For example:
> - Name: author
>     - Expression: `user()`
>     - Default value: Your Name
> - Name: date
>     - Expression: `date()`
>     - Default value: $YEAR-$MONTH-$DAY
> - Name: time
>     - Expression: `time(”HH:mm:ss”)` → You can change the format if you want
>     - Default value: `$HOUR:$MINUTE:$SECOND`
> - Name: description
>     - Expression: `groovyScript("''")`
>     - Default value: Description
Enter fullscreen mode Exit fullscreen mode
  1. Click OK to save the variables.
  2. Click OK again to save the live template.

Now, when you're editing a code file in IntelliJ IDEA, you can type your abbreviation (e.g., fileheader) and then press Tab to expand it into the documentation template, with placeholders automatically filled in according to your settings. You can then customize the placeholders as needed for each file.

Manually create

VS Code

  • In VS Code, you can create custom snippets to achieve similar functionality to live templates in IntelliJ IDEA. Here's how you can do it:

vscode

  1. Open VS Code.
  2. Go to File > Preferences > Configure User Snippets.
  3. Select the language for which you want to create the snippet, or choose "New Global Snippets File" to create a snippet that applies to all languages.
  4. If you selected a specific language, VS Code will open the corresponding language's snippets file (e.g., javascript.json for JavaScript). Otherwise, if you chose "New Global Snippets File," you can specify a file name for your snippets.
  5. In the snippets file, add your custom snippet. Here's an example for a JavaScript file header:
"File Header": { 
        "prefix": "fileheader", 
        "body": [ 
            "/**", 
            " * Description: $1", 
            " * Author: $2", 
            " * Date: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE", 
            " * Time: $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND", 
            ], 
            "description": "File Header" 
    }

Enter fullscreen mode Exit fullscreen mode

In this snippet:

  • "prefix" is the keyword you'll type to trigger the snippet.
  • "body" contains the lines of code that will be inserted when the snippet is triggered. You can use placeholders like $1, $2, etc., to define points where you'll be prompted to enter values.
  • "description" is an optional field that provides a description for the snippet.
  • Save the file.

Now, when you're editing a file in VS Code, you can type your snippet prefix (e.g., fileheader) and then press Tab to expand it into the template. You can then fill in the placeholders as needed.

VsCode header

On top of that…

While coding, we often find ourselves repeating certain pieces of code, like defining a restcontroller in Spring or creating React components. To avoid this redundancy and write code more efficiently, you can customize your templates to automate the generation of repetitive code segments. This way, you can streamline your development process and focus more on the unique aspects of your application.

For example

restcontroller

@RestController
@RequestMapping("/api")
public class $ControllerName$ {

    @GetMapping("/$endpoint$")
    public ResponseEntity<String> $methodName$() {
        // Controller logic
        return ResponseEntity.ok("Hello, world!");
    }
}
Enter fullscreen mode Exit fullscreen mode

rcomp

import React from 'react';

const $ComponentName$ = () => {
    return (
        <div>
            {/* Component content */}
        </div>
    );
};

export default $ComponentName$;
Enter fullscreen mode Exit fullscreen mode

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$Title$</title>
</head>
<body>
    <!-- Content goes here -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Hit the Tab and magic happen!

Rest controller

Final Thought

I think there are many ways to boost productivity at work, and using templates is a great method. If you have any helpful templates to share, please feel free to do so below. Thank you!

Top comments (0)