简体   繁体   English

在 Freemarker 中处理 null

[英]Handling null in Freemarker

Situation:情况:

  • Old java project using freemarker has many finished templates working great.使用 freemarker 的旧 java 项目有许多完成的模板工作得很好。
  • Every template is using data form Transaction object.每个模板都使用数据表单事务对象。
  • This transaction object is very large, because wraps all data about transaction.这个交易对象非常大,因为它包含了所有关于交易的数据。
  • In templates is a lot of expression like this: get("object1").getNestedObject2().getNestedObject3().getValue();在模板中有很多这样的表达式: get("object1").getNestedObject2().getNestedObject3().getValue();

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:不满意的解决方案:

  1. Remake all templates to check null values.重新制作所有模板以检查空值。 (Lot of work and not safe) (工作量大,不安全)
  2. Create Transaction object that contains all default value.创建包含所有默认值的事务对象。 (Lot of work) (很多工作)

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 运行,根TemplateModelObjectWrapper ,因此它可以控制模板为什么名称获取什么值。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM