Search code examples
javaapachevelocity

What is Apache Velocity?


Can someone please explain, what is Apache Velocity ? what is its purpose ?

It would be nice to provide an example along with it.

Thanks in advance.


Solution

  • Apache Velocity is a template engine. That means that you can add variables to a context, load a template in which those variables are referenced and render a text from this template where the references to the variables are replaced with the variable's actual value.

    It's purpose is to separate design and static content from code. Take a website for example. You don't want to create HTML inside your java code, do you? You would have to recompile your app every time you change a bit of design and you would polute your code with unnecessary design clutter. You would rather want to get your variables, either computed or from a database or whatever and have a designer create a HTML template in which your variables are used.

    Some pseudo code to make it clear:

    /* The user's name is "Foo" and he is of type "admin"*/
    User user = getUserFromDatabase("Foo");
    
    /* You would not add hard coded content in real world.
     * it is just to show how template engines work */
    String message = "Hello,";
    
    Velocity.init(); /* Initialises the Velocity engine */
    
    VelocityContext ctx = new VelocityContext();
    
    /* the user object will be available under the name "user" in the template*/
    ctx.put("user",user); 
    /* message as "welcome" */
    ctx.put("welcome",message);
    
    StringWriter writer = new StringWriter();
    
    Velocity.mergeTemplate("myTemplate.vm", ctx, writer);
    
    System.out.println(writer);
    

    Now given a file called myTemplate.vm

    ${welcome} ${user.name}!
    You are an ${user.type}.
    

    The output would be:

    Hello, Foo!
    You are an admin.
    

    Now let's assume the flat text should be HTML instead. The designer would change myTemplate.vm to

    <html>
    <body>
      <h1>${welcome} ${user.name}</h1>
      <p>You are an ${user.type}</p>
    </body>
    </html>
    

    So the output would be a html page without a single change in the java code.

    So the use of a template engines like Velocity (there are others, e.g. Thymeleaf or Freemarker) let designers do a designer's job and programmers do a programmer's job with minimal interference to each other.