Tagged: template engine Toggle Comment Threads | Keyboard Shortcuts

  • Mathew Varghese 3:40 pm on February 18, 2009 Permalink |
    Tags: , , template engine, ,   

    Velocity Template Engine – Part 2 (Getting templates from a JAR) 

    In my previous post I described the basics of Velocity template engine. In that post, we were making use of a template (the .vm file) which we keep outside the application archive. But there are some potential issues in doing that – sometimes those file may get corrupted or deleted. So a better idea will be to keep it with in the application archive itself. In this post I will explain how we can make use of a template file with in an archive.

    Sample Template Filetestvelocity.vm

    Hello $name! Welcome to Velocity!

    Java ProgramTestVelocity.java

    A java program that refers to the the testvelocity.vm template.

    public static void handleTemplate()
    {
    	VelocityEngine engine = null;
    	String myTemplateBody = null;
    	VelocityContext context = null;
    	StringResourceRepository repository = null;
    	Template template = null;
    	StringWriter writer = null;
    
    	try
    	{
    		// Getting Velocity Engine
    		engine = getVelocityEngine(engine);
    
    		// Reading Template Body from the template file(.vm file) in the jar
    		myTemplateBody = getTemplateFromJar();
    
    		// Setting the template body in string repository with a template
    		// name. Here the template name is used as a key for future mapping.
    		repository = StringResourceLoader.getRepository();
    		repository.putStringResource("myTemplateName", myTemplateBody);
    
    		// Getting the context with placeholder values
    		context = getVelocityContext();
    
    		// Fetch Template to a StringWriter
    		template = engine.getTemplate("myTemplateName");
    		writer = new StringWriter();
    		template.merge(context, writer);
    
    		System.out.println("VM Template:\n" + myTemplateBody);
    		System.out.println("Output:\n" + writer.toString());
    	}
    	catch (Exception e)
    	{
    		System.out.println("Oops! We have an exception");
    		e.printStackTrace();
    	}
    
    }
    

    Getting the template engine
    Velocity supports different kind of resource loaders.  In this context we need to use a String resource loader. Know more about it here.

    private static VelocityEngine getVelocityEngine(VelocityEngine engine)
    throws Exception
    {
    	// Initializes the velocity engine with properties. We should specify
    	// the resource loader as string and the class for
    	// string.resource.loader in properties
    	Properties p = new Properties();
    
    	p.setProperty("resource.loader", "string");
    	p.setProperty("string.resource.loader.class",
    		"org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    	engine = new VelocityEngine();
    	engine.init(p);
    
    	return (engine);
    }
    

    Getting Template file from JAR
    Know more about JAR and deployment here.

    // Reading the file contents from the JAR
    inStream = TestVelocity.class
    		.getResourceAsStream("/path/to/velocity/template/testvelocity.vm");
    stringBuilder = new StringBuilder();
    streamReader = new InputStreamReader(inStream);
    bufferedReader = new BufferedReader(streamReader);
    
    while ((line = bufferedReader.readLine()) != null)
    {
    	stringBuilder.append(line);
    }
    

    Getting Velocity context

    context = new VelocityContext();
    context.put("name", "mathew");
    

    Output

    Velocity console out

    Please check this post get additional information on building a JAR file & executing it: https://javabeanz.wordpress.com/2009/01/29/running-an-executable-jar-from-command-line/

     
    • chrcharles 11:44 pm on October 26, 2009 Permalink

      Hello Subin,
      Thanks for your post, but i misunderstand the Getting Template file from JAR’ code !?

      How do you transform StringBuilder instance to a Template instance ?

      Bests regards.

      Chris

    • Subinkrishna G 11:52 am on October 28, 2009 Permalink

      Hi Chris,

      Thank you for the comment. “Getting the template from JAR” means, reading the contents of a template which is been deployed as a part of a JAR. The usual practice is to deploy the template not as a part of the JAR or WAR so that any one can modify it.

      So, the above method will read the template contents as a stream of bytes (and then as a String object) and will attach it to the corresponding repository.

      The line, myTemplateBody = getTemplateFromJar(); in the above code block reads the template as a String. I’ve not given the complete implementation of getTemplateFromJar().

      Subin

    • Subinkrishna G 11:55 am on October 28, 2009 Permalink

      We can convert the StringBuilder to a String by calling the toString().

      Subin

  • Mathew Varghese 5:25 pm on February 13, 2009 Permalink |
    Tags: , , template engine, ,   

    Velocity Template Engine 

    Velocity is an open source template engine developed by an international volunteer community and hosted by the Apache Software Foundation.

    A template engine is a software that is designed to process web templates and content information to produce output web documents. Any velocity project contains two things – Velocity Template & Java Program.

    Velocity Template
    A velocity template is a text or text file (with .vm extension – that’s the general practice), that contains normal text and velocity specific placeholders (e.g. $name).

    A sample template file testvelocity.vm

    My name is $name

    Java ProgramTestVelocity.java
    A java program that refers to the the testvelocity.vm template.

    import java.io.StringWriter;
    import org.apache.velocity.app.VelocityEngine;
    import org.apache.velocity.Template;
    import org.apache.velocity.VelocityContext;
    public class TestVelocity
    {
    	public static void main( String[] args )
    	throws Exception
    	{
    		// Initializes engine
    		VelocityEngine ve = new VelocityEngine();
    		ve.init();
    
    		// Getting the Template
    		Template temp = ve.getTemplate("testvelocity.vm");
    
    		// Create a context and add data to the template placeholder
    		VelocityContext context = new VelocityContext();
    		context.put("name", "Velocity");
    
    		// Fetch template into a StringWriter
    		StringWriter wr = new StringWriter();
    		temp.merge( context, wr );
    		System.out.println( wr.toString() );
    	}
    }
    

    Output
    When you compile and run,the output will be;

    My name is Velocity

    Note:
    The template file is expected to be in the class-path. If you want to load a template file, add the following code block to the code.

    Properties velocityProperties = new Properties();
    velocityProperties.setProperty("file.resource.loader.path",
        "/path/to/my/velocity/template/dir");
    
    // Use this properties to initialize the engine
    VelocityEngine ve = new VelocityEngine();
    ve.init(velocityProperties);
    

    Directives – What is it?
    There are different directives for velocity.

    #set(), #if(), #else, #elseif(), #end, #foreach(), #include(), #parse(), #macro()

    Example:

    #if ( $value > 10 )
    display me. I am greater than 10.
    #elseif ( $value < 10 ) display me. I am lesser than 10. #else display me. #end [/sourcecode] I will be adding more about it in my future posts.

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel