将Java代码嵌入模板中 [英] embed java code inside a template
问题描述
是否可以在ST4模板中嵌入可执行的Java代码?例如,如果我想将一个字符串传递给我的模板,该模板有时按原样打印该字符串,有时将其打印成大写字母,那么我希望一个Java代码进行必要的转换.没有此功能,我将看到三种实现相同功能的方法:
Is it possible to embed executable java code inside a ST4 template? eg if I want to pass a string to my template, which sometimes prints the string as-is, and sometimes prints it in caps, so I want a java code to do the necessary conversion. Without this feature, I see 3 ways to achieve the same functionality:
(1)预计算Java中的替代值,并将它们一次全部传递给模板(但这可能会导致过多的参数):
(1) pre-compute the alternative values in java, and pass them all to the template at one shot (but this may result in too many arguments):
// in the below code, if the template can compute DESCRIPTION_CAPS from DESCRIPTION, using embedded java code, that reduces one argument
test(DESCRIPTION, DESCRIPTION_CAPS) ::= <<
this is original <DESCRIPTION>
this is caps <DESCRIPTION_CAPS>
>>
(2)如果出现太多这样的论点,另一种选择是将词条分解成更小的部分,但这会使代码难看且不可读:
(2) If there become too many such arguments, the other option is to break up the temlpate into smaller parts, but that makes the code ugly and unreadable:
test1(DESCRIPTION) ::= <<
this is original <DESCRIPTION>
>>
test2(DESCRIPTION_CAPS) ::= <<
this is caps <DESCRIPTION_CAPS>
>>
(3)预计算类中的所有相关值,然后让模板调用getter函数(不带参数)以简单地从类中获取相关值.
(3) Pre-compute all relevant values inside a class, and let the template call the getter functions (without arguments) to simply get the relevant values from the class.
test() ::= <<
this is original <values.description>
this is caps <values.description_caps>
>>
到目前为止(如果没有可用的嵌入java类),第3个选项似乎是最好的解决方案.请告知是否存在更好的解决方案.
As of now (if the embedding java class is not available) the 3rd option looks like the best solution. Please advise if a better solution exists.
注意:在上面的示例中,我仅以CAPS为例,可能还需要更复杂的Java函数.
Note: in the above example, I have used CAPS as only as an example, there could be more complex java functions also needed.
推荐答案
正如@Hartmut所说,不,您不能在模板中嵌入Java代码,但可以创建自定义
As @Hartmut said, no you can't embed java code inside a template, but you can create a custom StringRenderer that you could use to format the strings in the way you want.
然后您可以像这样将自定义格式字符串传递给渲染器:
You could then pass your custom format string to the renderer like this:
test(description) ::= <<
this is original <description>
this is caps <description; format="upper">
this is custom format <description; format="my-format-string">
>>
P.S如果您只想更改文本大小写,则可能不需要自己动手,只需添加对StringTemplate随附的StringRenderer的引用,即可:
P.S if you're just interested in changing the text case you might not need to roll your own, just add a reference to the StringRenderer that comes bundled with StringTemplate using:
templateGroup.registerRenderer(String.class, new StringRenderer());
并传递"upper","lower"或"cap"作为格式字符串
and pass "upper", "lower", or "cap" as the format string
这篇关于将Java代码嵌入模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!