Code Like a Pro: How to use templates in IntelliJ IDEA & VS Code
Tags: beginners, programming, productivity, development
Published: 2024-04-28 07:01:44

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/us5qbqz73m9gm5bvxixe.png)


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
    
    ```java
    /**
     * ${NAME}
     *
     * @author Your Name
     * Date: ${DATE} 
     * Time: ${TIME}
     */
    ```
    
6. Apply and OK

![Auto generate](https://res.cloudinary.com/drn3o5oc4/image/upload/v1714267925/devto/vhud8zaud2oa2wf7uf4m.gif)


#### Manually create header file with Live Template


![Manually template setting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2g429j40kppqzqymgbi.png)

- 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

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


![Result ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdijb275yy0owv46zfn6.png)


    > 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


7. Click **`OK`** to save the variables.
8. 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](https://res.cloudinary.com/drn3o5oc4/image/upload/v1714286621/manually-header-file-ezgif.com-video-to-gif-converter_f8g79f.gif)


### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i30jf24c0xe49kw5zdcm.png)


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:

```json
"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" 
	}

```

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.
5. 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](https://res.cloudinary.com/drn3o5oc4/image/upload/v1714286912/vscode-header-file-ezgif.com-video-to-gif-converter_va7wlc.gif)

## 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`

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

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

`rcomp`

```react
import React from 'react';

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

export default $ComponentName$;
```

`html`

```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>
```

Hit the Tab and magic happen!

![Rest controller](https://res.cloudinary.com/drn3o5oc4/image/upload/v1714287070/restcontroller-ezgif.com-video-to-gif-converter_tfwnih.gif)

## 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!