You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Apache FreeMarker中实现首字母大写其余小写的文本格式化?

在Apache FreeMarker中实现文本格式化(首字母大写统一格式)

方法1:使用内置函数组合快速实现

无需额外定义格式化器,直接通过FreeMarker内置字符串函数组合即可完成需求:

# 处理全大写字符串
${'ANIMAL'?lower_case?capitalize}  # 输出: Animal

# 处理全小写字符串
${'animal'?lower_case?capitalize}  # 输出: Animal

# 处理从JSON获取的变量
${jsonData.animalType?lower_case?capitalize}
  • ?lower_case:将整个字符串转为小写
  • ?capitalize:将字符串首字符转为大写,其余保持小写,刚好适配统一格式需求

方法2:自定义模板宏实现复用

如果需要在模板中多次使用该格式化逻辑,可以定义可复用的宏:

<#macro formatWord str>
    ${str?lower_case?capitalize}
</#macro>

使用方式:

<@formatWord str='ANIMAL'/>          # 输出: Animal
<@formatWord str=jsonData.animalType/>  # 处理JSON变量

方法3:自定义全局Java函数(适用于Java项目)

如果需要在所有模板中全局复用,或者需要更复杂的格式化逻辑,可以通过Java自定义FreeMarker方法:

  1. 实现TemplateMethodModelEx接口:
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import java.util.List;

public class CapitalizeWordMethod implements TemplateMethodModelEx {
    @Override
    public Object exec(List args) throws TemplateModelException {
        if (args.size() != 1) {
            throw new TemplateModelException("formatWord方法仅接受一个字符串参数");
        }
        String input = args.get(0).toString();
        if (input == null || input.isEmpty()) {
            return "";
        }
        return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
    }
}
  1. 注册到FreeMarker配置:
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
// 完成模板加载路径、编码等基础配置...
cfg.setSharedVariable("formatWord", new CapitalizeWordMethod());
  1. 在模板中调用:
${formatWord('animal')}  # 输出: Animal
${formatWord(jsonData.animalType)}

内容的提问来源于stack exchange,提问作者diho472

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:20:22