【问题标题】:Pass Java function in Velocity template在 Velocity 模板中传递 Java 函数
【发布时间】:2017-03-31 07:47:27
【问题描述】:

我被困在这个问题上。

public String getMessage(String id)
{
    log.error("passing parameter "+id+" "+id.getClass().getName());
    if(id.compareTo("1")==0)
    {
        return "nothing perfect";
    }
    else {return "All done";}
}

.vm

#set($parameter="1")
#set($message = $action.getMessage("$parameter").show())
<td>$message</td>`

在呈现的 HTML 中,我得到 $message。为什么我没有收到实际消息?

【问题讨论】:

  • 改为“1”.equals(id)
  • 没有改变

标签: java velocity vtl


【解决方案1】:

来自 Velocity 文档:

Velocity 只是真实 Java 对象的一个​​外观......

因此,要访问 Velocity 模板中类的公共方法,相关类的对象应该对 Velocity 模板可见

public class MessageSource {

    public String getMessage(String id){
        log.error("passing parameter "+id+" "+id.getClass().getName());
        if(id.compareTo("1")==0){
            return "nothing perfect";
        } else { 
            return "All done";
        }
    }

}

现在公开MessageSource的对象:

/*  first, get and initialize an engine  */
VelocityEngine ve = new VelocityEngine();
ve.init();
/*  next, get the Template  */
Template t = ve.getTemplate( "helloworld.vm" );
/*  create a context and add data */
VelocityContext context = new VelocityContext();
context.put("messageSource", new MessageSource());
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );  

所以,在你的速度模板中...

$messageSource.getMessage("identifier")

【讨论】:

    【解决方案2】:

    你不能直接在velocity中传递函数。

    Test.java

    public class Test {
    
        Message mg = new Message(); 
        context.put("formatter", mg);         
    }
    

    Message.java

    public class Message {
    
        public String getMessage(String id){
            log.error("passing parameter "+id+" "+id.getClass().getName());
            if(id.compareTo("1")==0){
                return "nothing perfect";
            } else { 
                return "All done";
            }
        }
    }
    

    example.vm

    #set($parameter="1")
    #set($message = $formatter.Message($parameter))
    <td>$message</td>
    

    【讨论】:

    • 很好的答案,但需要解释。
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2021-09-26
    相关资源
    最近更新 更多