FreeMarker模板编写指南

关于代码生成器项目中的代码模板编写指南

此文档搭配代码生成器工具使用:https://github.com/hczs/code-generator

项目已有参数

参数配置表单参数:

参数名参数含义模板中使用
author作者${author}
groupName模板组名称${groupName}
email邮箱${email}
ignorePrefix忽略表名前缀${ignorePrefix}
permission权限标识${permission}
requestMappingURL映射路径${requestMapping}

表 SQL 语句会解析为 classInfo 对象,SQL 相关信息会映射为这个对象的属性值

参数名参数含义模板中使用
classInfo.originTableName原始表名${classInfo.originTableName}
classInfo.tableName表名(去掉表名前缀后)${classInfo.tableName}
classInfo.className类名(实体类的名字)${classInfo.className}
classInfo.classComment类注释${classInfo.classComment}

classInfo 对象还有一个 fieldList 属性,这个是 SQL 中各个字段的集合,使用的时候需要遍历

<#list classInfo.fieldList as fieldItem >
  字段名: ${fieldItem.fieldName}
  字段类型: ${fieldItem.fieldClass}
  字段注释信息: ${fieldItem.fieldComment}
</#list>

模板语法

完整文档请查看模板开发指南:http://freemarker.foofun.cn/dgui_quickstart_template.html

以下列出常用的语法

分支判断(if)

语法规则:<#if condition> xxx </#if>

  • condition:可以是一个判断句式,比如 author == “sunnyc”
  • xxx: 是 condition 为 true 的时候,会显示 xxx 内容,如果为 false,则什么都不显示

实际使用样例,如果字段类型为 Date,则加上后面的 dateFormat 内容:

<#if fieldItem.fieldClass == "Date">, dateFormat = "yyyy-MM-dd HH:mm:ss"</#if>

循环(list)

语法规则:<#list sequence as loopVariable> repeatThis </#list>

  • sequence:是我们要遍历的目标对象
  • loopVariable:是目标对象里面的每一个元素
  • repeatThis:循环体内容

实际使用样例,我们遍历 classInfo 对象的 fieldList 属性,这个属性是一个 List 集合:

<#list classInfo.fieldList as fieldItem >
  字段名: ${fieldItem.fieldName}
  字段类型: ${fieldItem.fieldClass}
  字段注释信息: ${fieldItem.fieldComment}
</#list>

常用函数

  • 获取当前日期:${.now?string('yyyy-MM-dd HH:mm:ss')}
  • 求 list 的大小:${classInfo.fieldList?size}
  • 首字母小写:${classInfo.className?uncap_first}

参考:


FreeMarker模板编写指南
https://www.powercheng.fun/articles/4bfb823a/
作者
powercheng
发布于
2022年7月21日
许可协议