java - 在 Velocity 模板中传递 Java 函数

标签 java velocity vtl

我被困在这个问题上。

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。为什么我没有收到实际消息?

最佳答案

来自 Velocity 文档:

Velocity is just a façade for real Java objects...

因此,要访问 Velocity 模板中类的公共(public)方法,相关类的对象应该对 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")
<小时/>

关于java - 在 Velocity 模板中传递 Java 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40643537/

相关文章:

html - 带页眉和页脚的速度邮件

javascript - 使用javascript更改html中每个元素的标签

velocity - 在 Velocity 中包含文字 JSON 内容(避免 HTML 转义)

java - 访问对象内部的字段时,Velocity 模板不会去模板化

java - 为什么 FileOutputStream 的 write() 方法可以写入字符,而 OutputStreamWriter 却不能?

velocity - 如何在 Velocity 上使用 BungeeCord 消息 channel ?

java - 除了 Java 属性之外,还有其他方法可以保存树状数据吗?

javascript - 使用VelocityJS解析VTL时如何修复 "Unexpected token $ in JSON"

java - 在 xpath 中按文本查找元素不起作用 - selenium webdriver

java - Java 和 JSP 真的有那么大的不同吗?