如何从 FreeMarker 模板调用对象上的 java 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1362343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:10:47  来源:igfitidea点击:

How do I call java methods on an object from a FreeMarker template?

javafreemarker

提问by Graham

Is it possible to call a method that takes parameters from a Freemarker template?

是否可以调用从 Freemarker 模板获取参数的方法?

I have an object model that I'm trying to render with Freemarker into a web page. One of the objects has a method to get a sublist of it's contents - taking a parameter that is used to filter the list:

我有一个对象模型,我正在尝试使用 Freemarker 将其渲染到网页中。其中一个对象有一个方法来获取其内容的子列表 - 采用一个用于过滤列表的参数:

public List getunits(final String type);

public List getunits(final String type);

I know in JSP you can't do this directly, but you can write custom functions that will allow you to achieve the result you want. How do you solve this in Freemarker? Is it the same with writing custom functions? Or is there some way of actually calling this kind of function?

我知道在 JSP 中您不能直接执行此操作,但是您可以编写自定义函数来实现您想要的结果。你如何在 Freemarker 中解决这个问题?和写自定义函数一样吗?或者有什么方法可以实际调用这种函数?

采纳答案by ChssPly76

FreeMarker allows invoking methods that were made available through the model from within expressions.

FreeMarker 允许从表达式中调用通过模型可用的方法。

Assuming your object has been exposed as myBeanyou can invoke the method as follows:

假设您的对象已公开,myBean您可以按如下方式调用该方法:

<#list myBean.getunits("myType") as unit>
  do stuff with ${unit}
</#list>

You don't have to use <list>, of course, it's just there as an example since your method returns a list.

<list>当然,您不必使用,它只是作为示例,因为您的方法返回一个列表。

回答by monzonj

As ChssPly76said, you can just peform the method call from within a Freemarker template, as long as you expose the object in the model.

正如ChssPly76所说,只要在模型中公开对象,您就可以从 Freemarker 模板中执行方法调用。

But it's important to keep in mind that if your method returns NULL (for whatever reason), you are going to get a confusing

但重要的是要记住,如果您的方法返回 NULL(无论出于何种原因),您将感到困惑

Expression myBean.getunits() is undefined on line ....

To avoid this, you should better use myBean.getunits(...)!(notice the exclamation point).

为避免这种情况,您应该更好地使用myBean.getunits(...)!(注意感叹号)。

Learn more about how Freemarker handles nulls here: http://freemarker.org/docs/dgui_template_exp.html#dgui_template_exp_missing

在此处了解有关 Freemarker 如何处理空值的更多信息:http: //freemarker.org/docs/dgui_template_exp.html#dgui_template_exp_missing