[英]Handling null in Freemarker
Situation:情况:
Problem: New requirements appear: All templates have to be process for preview with no real data.问题:出现新要求:所有模板都必须经过处理才能进行预览,没有真实数据。 All numbers should be Zero and all string should be ---.
所有数字应为零,所有字符串应为 ---。
Unsatisfactory solutions:不满意的解决方案:
Well my question is: Can I say to Freemarker, that if he finds null or finds null along the way, that he should use 0 instead if he was expecting number or --- if he was expecting String.那么我的问题是:我可以对 Freemarker 说,如果他发现 null 或一路上发现 null,如果他期待数字或 --- 如果他期待 String,他应该使用 0 代替。
Or do you see any better solution?或者你有没有更好的解决方案?
If you need to show a dummy data model to the templates, your best bet is probably a custom ObjectWrapper
(see Configuration.setObjectWrapper
).如果您需要向模板显示虚拟数据模型,最好的选择可能是自定义
ObjectWrapper
(请参阅Configuration.setObjectWrapper
)。 Everything that reads the data model runs through the TemplateModel
-s, and the root TemplateModel
is made by the ObjectWrapper
, thus it can control what values the templates get for what names.读取数据模型的所有内容都通过
TemplateModel
-s 运行,根TemplateModel
由ObjectWrapper
,因此它可以控制模板为什么名称获取什么值。 But the question is, when you have to return a dummy value for a name, how can you tell what its type will be?但问题是,当您必须为名称返回一个虚拟值时,您如何知道它的类型是什么? It's not just about finding out if it will be a string or a number, but also if it will be a method (like
getNestedObject2
) or a hash (something that can be followed by .
).这不仅仅是要找出它是一个字符串还是一个数字,还要找出它是一个方法(如
getNestedObject2
)还是一个哈希(后面可以跟.
的东西)。 What can help there is that FreeMarker allows a value to have multiple types, so you can return a value that can be used as a method and as a hash and as a string, for example.有什么帮助是 FreeMarker 允许一个值具有多种类型,因此您可以返回一个可以用作方法、哈希和字符串的值,例如。 Depending on the application that hack is might be good enough, except, you still have to decide if the value is a string or a number, because
${}
will print the numerical value if the value both a string and a number.根据 hack 可能足够好的应用程序,除了,您仍然必须决定该值是字符串还是数字,因为如果值既是字符串又是数字,
${}
将打印数值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.