我想知道如何为字符串模板创建自定义格式函数。假设我有以下代码:
render(attributes) :: <<
<html>
$atributes: {
<div> $customformat(atribute.name)$</div>
}
</html>
>>
customformat(name) ::= <<
$name; format="upper"$
>>
当前自定义格式函数的行为是:
输入:“hello world” -> 输出:“HELLO WORLD”
我想修改 customformat 函数,使输出如下所示:
输入:“hello world” -> 输出:“HELLO_WORLD”
最佳答案
据我所知,这是不可能的,因为 StringTemplate 完全是关于严格的模型 View 分离。
相反,我认为最好在返回格式化字符串的 Controller 中使用 getter。
您可能会发现这个问题很有用:embed java code inside a template
实际上,我找到了一种简单的方法来做到这一点,避免了对格式化字符串 getter 的需要:
您需要创建一个新的 StringRenderer,它可以按照您想要的方式格式化字符串。
public class MyStringRenderer extends StringRenderer
{
@Override
public String toString(Object o, String formatString, Locale locale) {
if (!("upperAndUnder".equals(formatString)))
return super.toString(o, formatString, locale);
// we want upper case words with underscores instead of spaces
return ((String) o).replaceAll(" ", "_").toUpperCase(locale);
}
}
然后您需要让模板组了解新的渲染器:
public static void main(String[] args) {
STGroup templates = new STGroupFile("test.stg");
templates.registerRenderer(String.class, new MyStringRenderer());
ST renderTemplate = templates.getInstanceOf("render");
renderTemplate.add("attributes", new String[]{"blahh blahh I'm a string", "I'm another string"});
System.out.println(renderTemplate.render());
}
然后您可以像以前一样调用格式函数,但传递“upperAndUnder”作为参数:
group test;
delimiters "$","$"
render(attributes) ::= <<
<html>
$attributes:{ attribute | <div> $customFormat(attribute)$</div>}; separator="\n"$
</html>
>>
customFormat(name) ::= <<
$name; format="upperAndUnder"$
>>
打印:
<html>
<div> BLAHH_BLAHH_I'M_A_STRING</div>
<div> I'M_ANOTHER_STRING</div>
</html>
仅供引用:
关于stringtemplate - StringTemplate4 的自定义格式函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26891383/