gpt4 book ai didi

java - 速度:使用分隔符/前缀连接可选字段

转载 作者:行者123 更新时间:2023-12-01 04:15:59 26 4
gpt4 key购买 nike

在速度模板中用分隔符连接多个字段同时保留空或空字符串而不添加多余分隔符的最简洁/可读的方式是什么?

作为示例,我们有一个工具提示或约会,如下所示:

Appointment ($number) [with $employee] [-] [$remarks] [-] [$roomToVisit]

我使用括号来指示可选数据。填写后通常会显示为

Appointment (3) with John - serve Java coffee - ballroom

当 $remarks 为空但 $roomToVisit 不为空时,则变为:

Appointment (3) with John - ballroom

当 $roomToVisit 为空时,我们得到:

Appointment (3) with John - serve Java coffee

当两者都为空时:

Appointment (3) with John

奖励:还可以使字段前缀可选。当只有 $employee 为空时,我们应该得到:

Appointment (3) serve Java coffee - ballroom

理想情况下,我希望速度模板看起来与第一个代码框非常相似。如果这是不可能的,您将如何使用最少的分散注意力的代码标签来实现这一目标?

类似的想法(速度示例可能有帮助,但更加冗长):

最佳答案

我发现您可以通过将 Java 类注册为上下文中的工具来调用自己的 Java 方法。现有的示例是 DisplayTool 。我使用方法“pre”和可变参数方法“join”创建一个 VelocityStringUtil 类用于条件前缀和连接,并将其注册为:

context.put("text", new VelocityStringUtil());

使用它,以下模板创建预期的输出:

Appointment ($number)$text.pre(' ', $text.join(' - ', $text.pre('with ', $employee), $remarks, $roomToVisit))

正如您所看到的,它仍然有点难看,但我认为它比使用预定义指令更好(除非我遗漏了一些东西)。

关于java - 速度:使用分隔符/前缀连接可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com