{"id":5945,"date":"2018-02-27T20:57:01","date_gmt":"2018-02-27T20:57:01","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=5945"},"modified":"2018-02-27T20:57:01","modified_gmt":"2018-02-27T20:57:01","slug":"using-the-velocity-template-engine","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/using-the-velocity-template-engine\/","title":{"rendered":"Using the Velocity template engine"},"content":{"rendered":"<p>Velocity is a template engine written for Java. It allows us to take files (or strings) with embedded Velocity Template Language (VTL) code and transform the files (or strings) based upon supplied values.<\/p>\n<p>Let&#8217;s create a simple template file (by default we use the extension .vm and a good convention is to append it to the original extension file type, so you know what type of file you&#8217;re transforming) then we&#8217;ll use Velocity to transform the file.<\/p>\n<p>We&#8217;ll create a standard Maven layout project<\/p>\n<ul>\n<li>From IntelliJ create a new project and select Maven<\/li>\n<li>In the src\/test folder add a new directory names resources<\/li>\n<li>Mark the directory as test resources<\/li>\n<li>Add a folder to resources named templates<\/li>\n<li>Add the file template.txt.vm<\/li>\n<\/ul>\n<p>My template.vm looks like this<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nHello $name,\r\n\r\nThis is a $template_name template.\r\n<\/pre>\n<p>As you&#8217;ve probably guessed the $ prefix denotes a variable which we will supply to Velocity.<\/p>\n<p>The first thing we need to do is create the Velocity engine and then set it up to allow us to load our files from the resources folder, here&#8217;s the code for this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nVelocityEngine velocityEngine = new VelocityEngine();\r\nvelocityEngine.setProperty(\r\n   &quot;resource.loader&quot;, \r\n   &quot;file&quot;);\r\nvelocityEngine.setProperty(\r\n   &quot;file.resource.loader.class&quot;, \r\n   &quot;org.apache.velocity.runtime.resource.loader.FileResourceLoader&quot;);\r\nvelocityEngine.setProperty(\r\n   &quot;file.resource.loader.path&quot;, \r\n   &quot;src\/test\/resources&quot;);\r\n<\/pre>\n<p>Next up we create a VelocityContext which we use to supply our mappings to the variable names used within the template file. We do not include the $ when supplying the variable name. We simply supply key value pairs, where the key is a String which represents the variable name and the value is what we want to replace it with (this is an Object which can be more complex than just a String). For this example our value will just be a String, so we have the following<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nVelocityContext velocityContext = new VelocityContext();\r\nvelocityContext.put(&quot;name&quot;, &quot;PutridParrot&quot;);\r\nvelocityContext.put(&quot;template_name&quot;, &quot;MyPutridParrotTemplate&quot;);\r\n<\/pre>\n<p><em>Note: If we do not add a context mapping then the result will be the original $variable_name, unchanged.<\/em><\/p>\n<p>Finally, we want to actually &#8220;merge&#8221; (as Velocity calls the process) our context against the template and at the same time we&#8217;re going to convert the resultant &#8220;merged&#8221; template into a string<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nStringWriter writer = new StringWriter();\r\nTemplate template = velocityEngine.getTemplate(&quot;templates\/template.txt.vm&quot;);\r\ntemplate.merge(velocityContext, writer);\r\n\r\n\/\/ to prove it worked...\r\nSystem.out.println(writer.toString());\r\n<\/pre>\n<p>Running the above code we will get the output (as you would expect)<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nHello PutridParrot,\r\n\r\nThis is a MyPutridParrotTemplate template.\r\n<\/pre>\n<p><strong>Taking things a little further<\/strong><\/p>\n<p>As mentioned previously the value stored within the context is an Object, so we can store an array of values if we want.<\/p>\n<p>Let&#8217;s assume we have the following template file<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nHello $name,\r\n\r\nMy templates\r\n\r\n#foreach( $t in $template_name)\r\n    * $t\r\n#end\r\n<\/pre>\n<p>As you can see the VTL supports foreach loops, so if we change the code that assigns the template_name to the context to look like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();\r\nlist.add(&quot;Putrid&quot;);\r\nlist.add(&quot;Parrot&quot;);\r\n\r\nvelocityContext.put(&quot;template_name&quot;, list);\r\n<\/pre>\n<p>Our output will now be<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nHello PutridParrot,\r\n\r\nMy templates\r\n\r\n    * Putrid\r\n    * Parrot\r\n<\/pre>\n<p>Take a look at the <a href=\"http:\/\/velocity.apache.org\/engine\/1.7\/vtl-reference.html\" rel=\"noopener\" target=\"_blank\">VTL reference<\/a> for more options.<\/p>\n<p><strong>And finally<\/strong><\/p>\n<p>Finally for this post, it&#8217;s not unusual to have a string that represents the template, for example, maybe we get our templates from a web service or just load from another file location into memory.<\/p>\n<p>Here&#8217;s the full code for this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nString templateString = &quot;Hello $name,\\n\\nThis is a $template_name template.&quot;;\r\n\r\nRuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();\r\nStringReader reader = new StringReader(templateString);\r\nSimpleNode node = runtimeServices.parse(reader, &quot;Velocity Template&quot;);\r\n\r\nVelocityContext velocityContext = new VelocityContext();\r\nvelocityContext.put(&quot;name&quot;, &quot;PutridParrot&quot;);\r\nvelocityContext.put(&quot;template_name&quot;, &quot;MyPutridParrotTemplate&quot;);\r\n\r\nStringWriter writer = new StringWriter();\r\nTemplate template = new Template();\r\ntemplate.setRuntimeServices(runtimeServices);\r\ntemplate.setData(node);\r\ntemplate.initDocument();\r\n\r\ntemplate.merge(velocityContext, writer);\r\n\r\n\/\/ to prove it worked...\r\nSystem.out.println(writer.toString());\r\n<\/pre>\n<p>The key differences are how we create the <em>SimpleNode<\/em> and then create the <em>Template<\/em>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Velocity is a template engine written for Java. It allows us to take files (or strings) with embedded Velocity Template Language (VTL) code and transform the files (or strings) based upon supplied values. Let&#8217;s create a simple template file (by default we use the extension .vm and a good convention is to append it to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[161,204],"tags":[],"class_list":["post-5945","post","type-post","status-publish","format-standard","hentry","category-java","category-velocity"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5945","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=5945"}],"version-history":[{"count":6,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5945\/revisions"}],"predecessor-version":[{"id":5954,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5945\/revisions\/5954"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=5945"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=5945"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=5945"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}