Paulito
Paulito

Reputation: 3

Java : Applying a Velocity script dynamically

I'm building a little portlet with Struts MVC that searches/lists books from a webservice.

In my very first tests, I integrated the Velocity Tools in my Struts project with no problem.

The final step is to allow the user to choose if he wants to use velocity or not. If yes, the velocity script will come from a webservice as a String. I put the test in a JSP page so that I can apply the following algorithm :

List<Book> books = myWebservice.getAllBooks();
if (user.preference.vm = enabled ){
    String velocityScript = myWebservice.getARandomVelocityScript()
    renderTheBooks(velocityScript,books);
}
else{
    use JSP and/or struts tags to generate the content
}

The problem is at the renderTheBooks(velocityScript,books) line : How can I code it?

Thank you, regards.

(I know that the architecture can seem a little bit odd but please, let us discuss the renderTheBooks method rather. I will appreciate you understand that point.)

Upvotes: 0

Views: 239

Answers (2)

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

Velocity class offers you static convenience method:

public static boolean evaluate(Context context,
                           Writer writer,
                           String logTag,
                           Reader reader)

Assuming that reader contains your velocity template, and velocity was configured correctly you can evaluate it using this method

Upvotes: 1

Rupok
Rupok

Reputation: 2082

#foreach( $book in $books )
    $book
#end

This way you can render list of books in velocity.

Upvotes: 0

Related Questions