StringTemplate有没有办法将空字符串转换为null?

时间:2015-06-10 11:41:18

标签: stringtemplate stringtemplate-4

我遇到的情况是我需要在具有格式的对象属性列表中使用包装和锚点功能。

我可以在字符串模板中创建一个列表,然后去掉空值,如果它们只是直接属性访问。但是,我希望能够有条件地格式化一些属性。例如,给定模板。

PrintItem(item) ::= <<
<item.Count> <strip([item.Name, item.Value, PrintVat(item.Vat), item.Id]); separator=""\n"", anchor>
>>
PrintVat(vat) ::= "<if(vat)>Total VAT <vat><endif>"

和一个值为

的对象
Count = 2
Name  = Tasty Chicken
Value = £100
Vat   = £20
Id    = 1

会产生

2 Tasty Chicken
  £100
  Total VAT £20
  1

如果我传递了相同的对象,但Value的值为null,则会生成

2 Tasty Chicken
  Total VAT £20
  1

因为strip删除了null。但是,如果我传递Vat为null值的第一个对象,那么我得到

2 Tasty Chicken
  £100

  1

因为模板总是解析为空字符串。 那么有没有解决方法将空字符串转换为null?

这里有明显的解决方法 StringTemplate 3: how to filter a list? 不起作用,因为它会在模板上抛出编译异常。具体而言,它不喜欢'没有'作为地图的价值。如果我可以将该值显式映射为null,就像在该帖子中那样,我会得到我需要的东西。

0 个答案:

没有答案