📜 ⬆️ ⬇️

Eh, I do not like to write boilerplate, because there is IntelliJ IDEA and Apache Velocity

Good afternoon, Habr!

This article will discuss how to partially reduce the amount of code that you often have to type manually or copy-paste somewhere (God forbid) using IntelliJ IDEA , and more specifically with file and code templates. If you are not familiar enough with the advanced use of the capabilities of this IDE, then welcome under cat.

It's no secret that you often have to write boilerplates - from simply creating the program's entry point to annoying brackets in JSON. The community of programmers is constantly optimizing this process - frameworks, microlibs, template engines are released ... The IDE features in which you work are also greatly facilitated - for example, auto-substitution or the aforementioned file and code templates.
')

IntelliJ IDEA file and code templates


Suppose we want to create a file in the project. To do this, we open the project through our favorite IDE, press the hot-key Alt + 1, after which the panel with the project tree appears. Next, click PKM on the directory in which you want to create a new file. This context menu opens:

image

Here we are, of course, interested in the item "New".

image

As you can see, there are various options - a file with a .java extension (Java Class), a file with a .kt extension (Kotlin File / Class), a package, and so on. There is also a section with more specific names - HTML File, JavaFXApplication, Singleton. If you click on any of this, then create a file that contains several lines of code specific to a particular technology or pattern. This is all File and Code Templates, that is, file and code templates. And under all the templates there is a button “Edit File Templates ...” She is interested in us. Click it and see this window:

image

For the average Java programmer, the set of templates available in IDEA is rather poor. But he was given a rich opportunity to edit them using a template engine called Apache Velocity. About him there are several articles on Habré, for additional reading, I will leave the links at the bottom of the article.

What can he do? Consider the picture above. On the left there is a list of available templates (it is impressive, but this is a fiction, it is rather poor in utility), on top there are tabs with template categories, the center is occupied by a text field in which HTML code is written, and below is a large amount of text marked Description. Suppose that I am not a web developer and I don’t understand HTML, so we’ll choose another template - for example, Class.

image

Immediately notice the code is not similar to Java, interspersed with Java code. These are the Apache Velocity constructs.

Apache Velocity: how to do


We will not dive into the depths of the API and documentation, but let's look at the main points that will help us write our templates.

Typically, template constructs interfere with plain text, so the process is somewhat specific.

Main:

$variable_name - access to a variable. The name must begin with a Latin letter and contain only Latin letters, numbers, as well as the symbols "-" and "_".

#set($variable_name = "value") - assignment of a variable value for further use in the text.

#if(condition) stub #else stub #end is a conditional statement. Instead of stubs, you can substitute what should appear in the text if the condition is satisfied (or not).

#include("another_template.txt") - substitutes the contents of the specified file. Files available for use should be listed on the Includes tab.

#parse("another_template.txt") - does the same thing as #includes , but if the file contains a VTL (Velocity Template Language is the same as Apache Velocity), then it will also be executed.

#evaluate(string) - substitutes the parameter and executes the VTL contained in it.

Now about data types. VTL variables can be of the following types:


It is also worth noting that the string here corresponds to the String in Java, so it can call the methods contains() , matches() and so on.

Also for writing templates in Java there are several predefined variables. The most important is ${NAME} , which contains the file name; ${PACKAGE_NAME} containing the package name; There are variables for time, for example, ${DAY} , containing today; It is possible to declare your variables, the value of which you will be asked to specify when you will create a file using the written template. Like this: ${VARIABLE_NAME} . A complete list of all predefined variables is in the Description textbox.

Examples?


To clarify the above, we will write a few of our own templates. Click on the green plus sign in our window above the list of templates.

Application Entry Point


Once I discovered that Idea does not have class templates containing public static void main() . Quite (well, or I did not find them). My acquaintance with IntelliJ IDEA templates and VTL began with this - I decided to write my own template, with comments and vararg-s.

It turned out like this:

 public class ${NAME} { public static void main(String... args) { } } 

Everything is simple here. From VTL-specific toys, only ${NAME} , a predefined variable. But I can, for example, insert a comment containing today and the name of the author.

 /** * Today is ${DATE} * ${USER} is #if(${MINUTE}%1==0) the best #else not the best #end */ public class ${NAME} { public static void main(String... args) { } } 

Enter the name of the template and save it. After that, click PCM somewhere in your project (I advise you to create a test project, but you can play on production) -> New -> Your template. Enter the file name and see:

image

Sumptuously!

Template for JUnit4 tests


A more practical and beautiful example. By convention on the design of the code, test classes should have the word Test in the title. Take care of your memory and write this pattern:

 import junit.framework.TestCase; public class ${NAME}#if(!$NAME.contains("Test"))Test #end extends TestCase { @Override public void setUp() { } } 

Now, if we forget to add the word “Test” in the title when creating the test case, the template will do it for us!

Note : here we called the contains method on the string. To call string methods, you need to refer to a variable, omitting braces. The same applies to accessing the fields of arrays and map - no braces!

Now save the template and try to create a test for yourself. Again, click the RMB on any directory -> New -> Your test pattern. Enter a name (without the word “Test”), this file is created here:

image

But that is not all. Let's remove it and recreate it with the same name, but this time we add the word “Test” at the end of the name. What do we get? Absolutely, no two consecutive "Test" s.

image

Hidden text
In fact, I just inserted two identical pictures, but it does not matter. It is working!

A little about the scheme


At the very top of the “File And Code Templates” window there is a drop-down list, in which there are two items - “Default” and “Project”. What does it mean?

This means that you can create templates for all projects (“Default”), or only for the current one (“Project”). This is called Schemes, and specifically there are only two of them available in File and Code Templates, although in general settings there are more of them and you can create your own. Nevermind.

What to read


The Habra articles mentioned by me devoted to VTL

Yes, it is only one, because in the process of writing the second one was lost somewhere.

There is also an English guide from IntelliJ

But it does not reveal all the possibilities of template code standardization, although it gives a more complete characterization of template usability.

And Getting Started off. Apache Velocity website

Conclusion


File and Code Templates is a very powerful tool IntelliJ IDEA, which for some reason is not well lit. There are things that you immediately come across, starting to study the subject area, but the patterns are clearly not relevant here - and in vain. Urgently share this information with your friends and colleagues and have them write templates on VTL! Persuade your boss or the owner of your favorite open-source to plant a person to make out the contribution guides, inserting templates into them. It's comfortable!

Source: https://habr.com/ru/post/343232/


All Articles