IntelliJ IDEA:File and code templates
官方文档传送门html
File templates是一套在建立一个新的文件时被自动生成的内容的规范。取决于你将要建立的文件的种类,templates会在全部的那种文件中提供一套按照行业标准或大家团队协做的约定或考虑其它因素的初始化的格式化的代码。java
IDEA 为全部支持的文件类型提供了已经定义好的templates。templates会在使用者建立一个新文件时提示用户使用。被建议使用的文件类型的集合取决于项目(module)和配置,还取决于在项目工具窗口(Project tool window)中,你当前(要建立/插入新文件)的位置的性质。好比说,IDEA将不会在Java source和test目录歪的位置提示你建立一个java class类型的文件。apache
做用域问题
File templates在 Editor | File and Code Templates page of IntelliJ IDEA settings (Ctrl+Alt+S) 中被管理。这一设置页面的设置有两个做用域:框架
- 保存在默认做用域下的设置管理存在于整个workspace中templates。这些设置存储在
fileTemplates
下的 IDE configuration directory
- 保存在项目做用域下的设置管理其对应项目下的templates。这些设置被存储在项目文件夹下的
.idea/fileTemplates
。这些templates能够在团队成员间共享。
一开始,templates列表中只有由IDEA提供的预先定义好的templates。其中一些是internal的,这意味着它们不能被删除也不能被重命名。内置的templates的名字会用粗体展现。使用者调整过的和自定义的templates的名字以蓝色进行展现。ide
templates的分类
IDEA把templates分为如下几种进行使用,它们也分别对应设置页面中的几个tab:工具
- Files tab:其中都是能够被用来建立新文件的file templates。
- Includes tab:其中都是能够插入到file templates中的可被复用的内容的templates,好比说,设置一个文件头template,它能自动生成其被建立的时间,建立它的做者的名字。这个文件头就可被复用的嵌入到各类文件中。
- Code tab:其中都是为被IDEA用来创造各类各样的结构的代码片断所准备的internal templates。你能够修改这个tab下的template,但你不能建立该分类下的新的templates.
- Other tab:其中都是被各类各样的应用框架(如Android开发,EJB规范,Mybatis开发等等)所使用的templates。你能够编辑修改该tab下的已存在的内置的templates,但不能建立新的。
建立一个新的file/include template
下述步骤描述了如何建立一个新的file template。对于建立新的include templates来讲,步骤十分类似。idea
从头新建一个新的file template
- In the Settings/Preferences dialog (Ctrl+Alt+S), select Editor | File and Code Templates.
- On the Files tab, click
and specify the name, file extension, and body of the template.
- Apply the changes and close the dialog.
复制一个已经存在的file template
- In the Settings/Preferences dialog (Ctrl+Alt+S), select Editor | File and Code Templates.
- On the Files tab, click
and modify the name, file extension, and body of the template as necessary.
- Apply the changes and close the dialog.
把一个文件设置为一个file template
- Open a file in the editor.
- Choose Tools | Save File as Template from the menu.
- In the Save File as Template dialog that opens, specify the new template name and edit the body, if necessary.
- Apply the changes and close the dialog.
template的语法
File和code templates按照Velocity Template Language (VTL)语法书写。VLT语法使用了如下的构件:spa
- 写死的内容。包括代码,注释等等。这些内容会被原样展示。
- 变量(Variables),最后呈现时会被实际值替换。
- 命令:好比
#parse
#set
, #if
下面这个例子是在IDEA建立一个.java文件时的默认模板翻译
#if (${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
public class ${NAME} {
}
在这个模板中code
-
#if
命令被用来检查包名是否非空。若是非空,则为package声明增长由${PACKAGE_NAME}
变量指明的包名。
-
#parse
命令被用来在该template(或者说文件)中插入另外一个名为File Header.java的template的内容。
- 而后这个template声明了一个public class并使用
${NAME}
变量(存储了新文件的名字)指明的类名。
- 我怀疑这里的internal指的是被IDEA依赖的。也就是说IDEA要正常工做必须依靠的。由于这个找不到合适的短词语进行翻译,故在此说明,此后遇到该词不做翻译。
- (https://www.jetbrains.com/hel...