1

I'm stuck on this.

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>`

In the rendered HTML I get $message. Why am I not getting the actual message?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80

2 Answers2

4

From Velocity documentation:

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

So, to access the public methods of a class in the Velocity template, the object of the concerned class should be visible to the velocity template.

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";
        }
    }

}

Now to expose the object of 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() );  

So, in your velocity template...

$messageSource.getMessage("identifier")

Community
  • 1
  • 1
Jay
  • 1,089
  • 12
  • 29
3

You can't directly pass function in 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>