java - 在 Java Mustache 中为模板添加格式化功能
问题描述
我有一个 Java Mustache 应用程序,我需要应用一个函数以货币格式呈现它
我有我的模板
{{#currency}}{{number_to_format}}{{/currency}}
我的功能
HashMap<String, Object> scopes = new HashMap<String, Object>();
//Add date
scopes.put("number_to_format",BigDecimal.ONE);
scopes.put("currency", new TemplateFunction() {
public String apply(String input) {
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(new BigDecimal(input));
}
}
);
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("template.mustache");
mustache.execute(writer,scopes).flush();
我无法获取“输入”变量中的值,我总是得到变量名称“number_to_format”。如果我在函数中返回一个值,它将被渲染。
如何获得输入变量的数值?
解决方案
输入变量是一个传入的模板,您需要渲染它以获取值
因此再次使用相同的工厂和范围渲染它并获取值
HashMap<String, Object> scopes = new HashMap<String, Object>();
final MustacheFactory mf = new DefaultMustacheFactory();
// Add date
scopes.put("number_to_format", BigDecimal.ONE);
scopes.put("currency", new TemplateFunction() {
public String apply(String input) {
//render the input as template to get the value
Mustache mustache = mf.compile(new StringReader(input), "");
StringWriter out = new StringWriter();
mustache.execute(out, scopes);
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
return currency.format(new BigDecimal(out.toString()));
}
});
Mustache mustache = mf.compile("template.mustache");
mustache.execute(new PrintWriter(System.out), scopes).flush();
否则通过检查输入从 HashMap 中获取值
if(input.equals("{{number_to_format}}")){
input = scopes.get("number_to_format").toString();
}
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
return currency.format(new BigDecimal(input));
否则删除 "{{" 和 "}}" 并将其用作 hashmap 的键
推荐阅读
- asynchronous - 如何用 tokio_serde::SymmetricallyFramed::new() 编写类型定义?
- python - pandas - 将 1 个数据帧转换为两个具有外键的数据帧
- python - 游戏敌人随机消失
- javascript - 从内存 JavaScript 中获取所有 Blob
- scala - 如何在另一个宏执行中使用在一个 Scala 宏执行中创建和类型检查的“universe.Tree”?
- sql - 在 Oracle SQL 中使用存储过程将数据插入表中
- sql - SQL - 计数功能无法正常工作
- postgresql - 在这个后来的连接案例中,它是一个函数还是一个表?
- javascript - 无法通过 id 复制和重命名元素
- c++ - 本地编译的 C++ 代码循环不正确