Freemarker中的继承/instanceof检查 [英] Inheritance / instanceof checks in Freemarker

查看:153
本文介绍了Freemarker中的继承/instanceof检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用例是为用户提供借助模板引擎创建报告的可能性.因此,我提取了数据模型的相关部分,并将Freemarker集成为模板引擎. 到目前为止,它运行良好,但是现在我的数据模型在某些位置包含继承-但是Freemarker似乎不支持instanceof操作?如何解决这个问题?模型中还有其他支持继承的模板引擎吗?

虚构示例:

我有2个类别的汽车"和自行车",它们扩展了车辆".该模型包含一个车辆编队"类,其中包含一系列车辆.用户希望(借助模板)遍历该列表,并在汽车的情况下编写属性"countSeats",在自行车的情况下编写属性"frame size". Freemarker如何做到这一点?可以在任何模板引擎中完成吗?

非常感谢!

//不幸的是,由于列表中的车辆顺序(在上述示例中)是必不可少的,因此无法将带有超类的列表拆分为带有"concrete"对象的多个列表.

解决方案

没有为此内置的功能,但也不必如此.您可以编写自己的TemplateMethodModelEx,或将简单的Java帮助程序对象放入数据模型以执行几乎所有操作.或者,您可以将相关类放入数据模型中,例如root.put("Car", Car.class)等,然后使用Class的Java API,如下所示:<#if Car.isInstance(someObject)>

my use case is to provide the user the possibility to create reports with the help of a template engine. Therefore I extracted the relevant part of my data model and integrated Freemarker as template engine. So far it worked great, but now my data model contains inheritance on some positions - but Freemarker does not seem to support instanceof operations? How to deal with this problem? Are there any other template engines which support inheritance in the model?

Fictive example:

I have 2 classes "Car" and "Bike" which extends "Vehicle". And the model contains a class "vehicle fleet" which contains a list of vehicles. User wants ( with the help of a template) to iterate through the list and write in case of a car the attribute "countSeats", in case of a bike the attribute "frame size". How can this be achieved with Freemarker? Can it be done in any template engine?

Many thanks in advance!

// Edit: Unfortunately it's not possible to split the list with the superclasses in several lists with the 'concrete' objects since the order of vehicles (in the above example) within the list is essential.

解决方案

There's nothing built in for this, but it doesn't have to be either. You can write your own TemplateMethodModelEx, or put plain Java helper objects into the data-model to do pretty much anything. Or, you can just put the relevant classes into the data-model, like root.put("Car", Car.class) etc., and then use the Java API of Class like this: <#if Car.isInstance(someObject)>

这篇关于Freemarker中的继承/instanceof检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆