Alexander Verzakov
Alexander Verzakov

Reputation: 21

Pass Java function in Velocity template

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?

Upvotes: 1

Views: 6290

Answers (2)

Jay
Jay

Reputation: 1119

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")

Upvotes: 4

ramgopal chaudhary
ramgopal chaudhary

Reputation: 224

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>

Upvotes: 3

Related Questions