StringTemplate4的自定义格式功能 [英] Custom format functions for StringTemplate4
问题描述
我想知道如何为字符串模板创建自定义格式功能.假设我有以下代码:
I would like to know how to create a custom format function for string template. Let say I have the following code:
render(attributes) :: <<
<html>
$atributes: {
<div> $customformat(atribute.name)$</div>
}
</html>
>>
customformat(name) ::= <<
$name; format="upper"$
>>
当前customformat函数的行为是:
Currently the behaviour of the function customformat is:
输入:"hello world"->输出:"HELLO WORLD"
Input: "hello world" -> Output: "HELLO WORLD"
我想修改customformat函数,使输出类似于以下内容:
And I would like to modify the customformat function so the output is something like the following:
输入:"hello world"->输出:"HELLO_WORLD"
Input: "hello world" -> Output: "HELLO_WORLD"
推荐答案
据我所知这是不可能的,因为StringTemplate都是关于严格的模型视图分离的.
As far as I'm aware this isn't possible, since StringTemplate is all about strict model-view separation.
相反,我认为您最好在返回格式化字符串的控制器中使用吸气剂.
Instead, I think you'd be better off having a getter in the controller that returned the formatted string.
您可能会发现此问题很有用:将Java代码嵌入模板中
You might find this question useful: embed java code inside a template
实际上,我找到了一种简单的方法来避免使用格式化的字符串获取器:
Actually, I found a simple way of doing this which avoids the need for the formatted string getters:
您需要创建一个新的StringRenderer,以所需的方式格式化字符串.
You need to create a new StringRenderer which can format the string in the way you want.
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);
}
}
然后,您需要让模板组了解新的渲染器:
Then you'll need to let the template group know about the new renderer:
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());
}
然后,您可以像以前一样调用format函数,但是将"upperAndUnder"作为参数传递:
Then you can call the format function like you did before, but pass "upperAndUnder" as the parameter:
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>
仅供参考:
这篇关于StringTemplate4的自定义格式功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!