在java指令中调用freemarker函数

dddzy1tm  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(262)

我有一个简单的freemarker模板,它定义了一个函数,并用函数作为参数调用一个java实现的指令:

<#function printParameter param>
    <#return "<td>"+param+"</td>"/>
</#function>

<@testCallFunctionDirective functionName="printParameter"/>

指令的java实现如下:

public class TestCallFunctionDirective implements TemplateDirectiveModel {

  private static final String FUNCTION_NAME_KEY = "functionName";

  @Override
  public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {

    String functionName = retrieveFunctionName(params);
    TemplateModel templateModel = env.getCurrentNamespace().get(functionName);
    String parameter = "param1";
    String functionCall = ! StringUtils.isEmpty(functionName) ? writeFunctionCall(functionName, parameter) : functionName;

    String builder = "Test table :"
        + "<br>-------"
        + "<table border='1'><tr>" + functionCall + "</tr></table>"
        + "<br>-------";
    env.getOut().write(builder);
  }

  private String retrieveFunctionName(Map<?,?> params) {
    return Optional.ofNullable(params.get(FUNCTION_NAME_KEY)).map(Object::toString).orElse(StringUtils.EMPTY);
  }

  private String writeFunctionCall(String functionName, String parameter) {
    //String functionCall = "<@.vars[" + functionName + "] "+parameter + "/>";
    String functionCall = "${"+functionName+"('"+parameter+"')}";
    return functionCall;
  }

因此,我们的想法只是天真地输出对实际模板定义函数的调用,让freemarker呈现该部分,但显然找不到该函数,我得到以下错误消息:

freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:
==> printParameter  [in template "template" at line 511, column 48]
----
Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default v
alue like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These onl
y cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptiona
lVar.foo)??
----
----
FTL stack trace ("~" means nesting-related):
----
- Failed at: @printParameter "param1"  [in template "template" at line 511, column 46]

在输出之前,是否需要从java端呈现该函数?如何在java指令中访问和呈现该函数?
如有任何帮助/建议,我们将不胜感激。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题