Added: velocity/site/cms/trunk/content/engine/2.1/vtl-reference.mdtext URL: http://svn.apache.org/viewvc/velocity/site/cms/trunk/content/engine/2.1/vtl-reference.mdtext?rev=1854714&view=auto ============================================================================== --- velocity/site/cms/trunk/content/engine/2.1/vtl-reference.mdtext (added) +++ velocity/site/cms/trunk/content/engine/2.1/vtl-reference.mdtext Sun Mar 3 13:56:00 2019 @@ -0,0 +1,347 @@ +title: Apache Velocity Engine VTL Reference + +## VTL Reference - Contents + +[TOC] + +## About this Guide + +This guide is the reference for the Velocity Template Language (VTL). For more information, please also refer to the [Velocity User Guide](user-guide.html). + +Notations are given in a very approximative EBNF-like syntax, the goal is to remain readable. + +## References + +In the following syntax references, *identifier* refers to: + +<span class="blue">(</span> **a..z** <span class="bigger blue">|</span> **A..Z** <span class="bigger blue">|</span> **_** <span class="blue">)</span> <span class="blue">[</span> <span class="blue">(</span> **a..z** <span class="bigger blue">|</span> **A..Z** <span class="bigger blue">|</span> **0..9** <span class="bigger blue">|</span> **_** <span class="blue">)</span> <span class="blue">,</span> <span class="blue">(</span> **a..z** <span class="bigger blue">|</span> **A..Z** <span class="bigger blue">|</span> **0..9** <span class="bigger blue">|</span> **_** <span class="blue">), ...</span> <span class="blue">]</span> + +that is, a letter or an underscore followed by any number of letters, numbers and underscores. + +If the `parser.allows.dash.identifiers` configuration value is set to true, then the **-** dash is also allowed in identifiers (and must be surrounded by spaces to be interpreted as an arithmetic minus operator). + +### Variables + +Notation: + +**$** <span class="blue">[</span> **!** <span class="blue">]</span> <span class="blue">[</span> **{** <span class="blue">]</span> *identifier* <span class="blue">[</span> <span class="blue">[</span> **|** *alternate value* <span class="blue">]</span> **}** <span class="blue">]</span> + +Usage: + ++ *alternate value*: alternate expression to use if the reference is null, empty, false or zero + +Examples: + ++ Shorthand notation: `$mudSlinger_9` ++ Silent Shorthand notation: `$!mudSlinger_9` ++ Formal notation: `${mudSlinger_9}` ++ Silent Formal notation: `$!{mudSlinger_9}` ++ Alternate value: `${mudSlinger_9|$otherWheels}` + +*Note that for backward compatibility reasons, it's possible to enable '**`-`**' as a valid character in variables identifiers, [see the parser configuration section](configuration.html#parser-configuration).* + +### Properties + +Notation: + +**$** <span class="blue">[</span> **{** <span class="blue">]</span> *identifier* **.** *identifier* <span class="blue">[</span> <span class="blue">[</span> **|** *alternate value* <span class="blue">]</span> **}** <span class="blue">]</span> + +Usage: + ++ *alternate value*: alternate expression to use if the property is null, empty, false or zero + +Examples: + ++ Regular Notation: `$customer.Address` ++ Formal Notation: `${purchase.Total}` ++ Alternate Value: `${person.name|'John Doe'}` + +### Methods + +Notation: + +**$** <span class="blue">[</span> **{** <span class="blue">]</span> *identifier* **.** *identifier* **(** <span class="blue">[</span> *parameter list...* <span class="blue">]</span> **)** <span class="blue">[</span> <span class="blue">[</span> **|** *alternate value* <span class="blue">]</span> **}** <span class="blue">]</span> + +Usage: + ++ *alternate value*: alternate expression to use if the method returns null, empty, false or zero ++ *parameter list*: optional coma-separated list of expressions + +Examples: + ++ Regular Notation: `$customer.getAddress()` ++ Formal Notation: `${purchase.getTotal()}` ++ Regular Notation with Parameter List: `$page.setTitle( "My Home Page" )` ++ Alternate value: `${page.getTitle()|'Blank Page'}` + +VTL Properties can be used as a shorthand notation for VTL Methods that take *get* and *set*. Either *$object.getMethod()* or *$object.setMethod()* can be abbreviated as *$object.Method*. It is generally preferable to use a Property when available. The main difference between Properties and Methods is that you can specify a parameter list to a Method. + +Each method argument can be any valid VTL expression. + +## Directives + +### #set - Establishes the value of a reference + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **set** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *$ref* **=** <span class="blue">[</span> **"**, **'** <span class="blue">]</span> *arg* <span class="blue">[</span> **"**, **'** <span class="blue">]</span> ) + +Usage: + ++ *$ref* - The LHS of the assignment must be a variable reference or a property reference. ++ *arg* - The RHS of the assignment, *arg* is parsed (i.e. interpolated) if enclosed in double quotes, and not parsed if enclosed in single quotes. If the RHS evaluates to *null*, it is **not** assigned to the LHS. + +Examples: + ++ Variable reference: `#set( $monkey = $bill )` ++ String literal: `#set( $monkey.Friend = 'monica' )` ++ Property reference: `#set( $monkey.Blame = $whitehouse.Leak )` ++ Method reference: `#set( $monkey.Plan = $spindoctor.weave($web) )` ++ Number literal: `#set( $monkey.Number = 123 )` ++ Range operator: `#set( $monkey.Numbers = [1..3] )` ++ Object list: `#set( $monkey.Say = ["Not", $my, "fault"] )` ++ Object map: `#set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"})` + +The RHS can also be a simple arithmetic expression, such as: + ++ Addition: `#set( $value = $foo + 1 )` ++ Subtraction: `#set( $value = $bar - 1 )` ++ Multiplication: `#set( $value = $foo * $bar )` ++ Division: `#set( $value = $foo / $bar )` ++ Remainder: `#set( $value = $foo % $bar )` + +### #if/#elseif/#else - Output conditional on truth of statements + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **if** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *condition* **)** *output* [**#** <span class="blue">[</span> **{** <span class="blue">]</span> **elseif** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *condition* **)** *output* <span class="blue">]</span> <span class="blue">[</span> **#** <span class="blue">[</span> **{** <span class="blue">]</span> **else** <span class="blue">[</span> **}** <span class="blue">]</span> *output* <span class="blue">]</span> **#** <span class="blue">[</span> **{** <span class="blue">]</span> **end** <span class="blue">[</span> **}** <span class="blue">]</span> + +Usage: + ++ *condition* - Expression to evaluate. When its result is null, evaluate to false. Otherwise, check for conversion towards Boolean and non-emptiness as follow: + - return its value for a Boolean object, or the result of the getAsBoolean() method if it exists. + - if `directive.if.emptycheck` = `false` (`true` by default), stop here and consider it true. + - return whether an array is empty. + - return whether isEmpty() is false (covers String and all Collection classes). + - return whether length() is zero (covers CharSequence classes other than String). + - returns whether size() is zero (covers all Collection classes). + - return whether a Number *strictly* equals zero. + - return whether the result of getAsString() is empty (and false for a null result) if it exists. + - return whether the result of getAsNumber() *strictly* equals zero (and false for a null result) if it exists. + - consider the condition is `true` + ++ *output* - May contain VTL. + +Examples (showing different operators): + +Operator Name | Symbol | Alternative Symbol | Example +--------------|--------|--------------------|-------- +Equals Number | == | eq | `#if( $foo == 42 )` +Equals String | == | eq | `#if( $foo == "bar" )` +Object Equivalence | == | eq | `#if( $foo == $bar )` +Not Equals | != | ne | `#if( $foo != $bar )` +Greater Than | > | gt | `#if( $foo > 42 )` +Less Than | < | lt | `#if( $foo < 42 )` +Greater Than or Equal To | >= | ge | `#if( $foo >= 42 )` +Less Than or Equal To | <= | le | `#if( $foo <= 42 )` +Boolean NOT | ! | not | `#if( !$foo )` + +Notes: + +1. The == operator can be used to compare numbers, strings, objects of the same class, or objects of different classes. In the last case (when objects are of different classes), if at least one the two objects cannot be converted to a number, the toString() method is called on each object and the resulting Strings are compared. +2. You can also use brackets to delimit directives. This is especially useful when text immediately follows an `#else` directive. + + :::velocity + #if($foo == $bar)it's true!#{else}it's not!#end + +### #foreach - Loops through a list of objects + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **foreach** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *$ref* **in** *arg* **)** *statements* <span class="blue">[</span> **#** <span class="blue">[</span> **{** <span class="blue">]</span> **else** <span class="blue">[</span> **}** <span class="blue">]</span> *alternate statements* <span class="blue">]</span> **#** <span class="blue">[</span> **{** <span class="blue">]</span> **end** <span class="blue">[</span> **}** <span class="blue">]</span> + +Usage: + ++ *$ref* - The first variable reference is the item. ++ *arg* - May be one of the following: a reference to a list (i.e. object array, collection, or map), an array list, or the range operator. ++ *statements* - What is output each time Velocity finds a valid item in the list denoted above as *arg*. This output is any valid VTL and is rendered each iteration of the loop. ++ *alternate statements* - What is to display whenever Velocity did not enter the loop (when *arg* is null, empty, or doesn't have any valid iterator). + +Examples of the #foreach loop: + ++ Reference: `#foreach ( $item in $items ) $item #else no item #end` ++ Array list: `#foreach ( $item in ["Not", $my, "fault"] ) $item #end` ++ Range operator: `#foreach ( $item in [1..3] ) $item #end` + +Inside the #foreach loop, the following can be used: + ++ `$foreach.count` : 1-based loop index ++ `$foreach.index` : 0-based loop index ++ `$foreach.first` : true on the first iteration ++ `$foreach.last` : true on the last iteration ++ `$foreach.hasNext` : false on the last iteration ++ `$foreach.stop()` : exists the loop, synonym for `#break` + +The maximum allowed number of loop iterations can be controlled engine-wide with `velocity.properties`. By default, there is no limit: + + :::properties + # The maximum allowed number of loops. + directive.foreach.maxloops = -1 + +### #include - Renders local file(s) that are not parsed by Velocity + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **include** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *arg* <span class="blue">[</span> *arg2* ... *argn* <span class="blue">]</span> **)** + +Usage: + ++ *arg* - Refers to a valid file under TEMPLATE_ROOT. + +Examples: + ++ String: `#include( "disclaimer.txt" "opinion.txt" )`+ ++ Variable: `#include( $foo $bar )` + +### #parse - Renders a local template that is parsed by Velocity + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **parse** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *arg* **)**</p> + +Usage: + ++ *arg* - Refers to a template under TEMPLATE_ROOT. + +Examples: + ++ String: `#parse( "lecorbusier.vm" )` ++ Variable: `#parse( $foo )` + +Recursion permitted. See *parse_directive.maxdepth* in `velocity.properties` to change from parse depth. (The default parse depth is 10.) + +### #stop - Stops the template engine + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **stop** <span class="blue">[</span> **}** <span class="blue">]</span> + +Usage: + +This will stop execution of the current template. This is good for debugging a template. + +### #break - Stops the current directive + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **break** <span class="blue">[</span> **}** <span class="blue">]</span> + +Usage: + +This will break execution of the current content directive. This is good for exiting a #foreach loop early, but also works in other scopes. You can even pass the scope control reference for a specific outer scope to break execution of all scopes outward to the specified one. + +### #evaluate - Dynamically evaluates a string or reference + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **evaluate** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *arg* **)** + +Usage: + ++ *arg* - String literal or reference to be dynamically evaluated. + +Examples: + ++ String: `#evaluate( 'string with VTL #if(true)will be displayed#end' )` ++ Variable: `#evaluate( $foo )` + +### #define - Assigns a block of VTL to a reference + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **define** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *$ref* **)** *statement* **#** <span class="blue">[</span> **{** <span class="blue">]</span> **end** <span class="blue">[</span> **}** <span class="blue">]</span> + +Usage: + ++ *$ref* - Reference that is assigned the VTL block as a value. ++ *statement* - Statement that is assigned to the reference. + +Example: + ++ `#define( $hello ) Hello $who #end #set( $who = "World!") $hello ## displays Hello World!` + +### #macro - Allows users to define a Velocimacro (VM), a repeated segment of a VTL template, as required + +Format: + +**#** <span class="blue">[</span> **{** <span class="blue">]</span> **macro** <span class="blue">[</span> **}** <span class="blue">]</span> **(** *vmname* *$arg1* <span class="blue">[</span> **=** *def1* <span class="blue">]</span> <span class="blue">[</span> *$arg2* <span class="blue">[</span> **=** *def2* <span class="blue">]</span> *$arg3* <span class="blue">[</span> **=** def3 <span class="blue">]</span> ... *$argn* <span class="blue">[</span> **=** *defn* <span class="blue">]</span> ] **)** <span class="blue">[</span> *VTL code* <span class="blue">]</span> **#** <span class="blue">[</span> **{** <span class="blue">]</span> **end** <span class="blue">[</span> **}** <span class="blue">]</span> + +Usage: + ++ *vmname* - Name used to call the VM (*#vmname*) ++ *$arg1 $arg2* ... - Arguments to the VM. There can be any number of arguments, but the number used at invocation must match the number specified in the definition, unless there is a default value provided for missing parameters. ++ *def1, def2, ...* - Optional default values provided for macro arguments. If a default value is provided for an argument, a default value must also be provided to all subsequent arguments. ++ *VTL code* - Any valid VTL code, anything you can put into a template, can be put into a VM. + +Once defined, the VM is used like any other VTL directive in a template. + + :::velocity + #vmname( $arg1 $arg2 ) + +**Except**, that when you wish to call a VM with a body, then you must prefix the name of the VM with @. The content of that body may be referenced in the macro definition via $!bodyContent as many or few times as you like. + + :::velocity + #@vmname( $arg1 $arg2 ) here is the body#end + +VMs can be defined in one of two places: + +1. *Template library:* can be either VMs pre-packaged with Velocity or custom-made, user-defined, site-specific VMs; available from any template +2. *Inline:* found in regular templates, only usable when *velocimacro.permissions.allowInline=true* in `velocity.properties`. + +Since 2.0, when a macro argument is null or invalid, its rendering will display its local name. The following block of code: + + :::velocity + #macro( vmname $foo ) $foo #end + #vmname( $null ) + +will display `$foo`. If you wish to revert to the 1.x behavior (which is to display `$null`), you can set the `velocimacro.preserve.arguments.literals` configuration property to true (since 2.1). + +## Comments + +Comments are not rendered at runtime. + +### Single Line Comments + +Example: + + :::velocity + ## This is a comment.** + +### Multi Line Comments + +Example: + + :::velocity + #* + This is a multiline comment. + This is the second line. + *# + +## Unparsed Content + +Unparsed content is rendered at runtime, but is not parsed or interpreted. + +Example: + + + :::velocity + #[[ + + This has invalid syntax that would normally need + "poor man's escaping" like: + + - #define() + - ${blah + + ]]# +
Added: velocity/site/cms/trunk/content/engine/2.1/webapps.mdtext URL: http://svn.apache.org/viewvc/velocity/site/cms/trunk/content/engine/2.1/webapps.mdtext?rev=1854714&view=auto ============================================================================== --- velocity/site/cms/trunk/content/engine/2.1/webapps.mdtext (added) +++ velocity/site/cms/trunk/content/engine/2.1/webapps.mdtext Sun Mar 3 13:56:00 2019 @@ -0,0 +1,180 @@ +Title: Apache Velocity Engine - Webapps Integration + +## Building a Web Application with Velocity + +Velocity is often used to generate web pages in applications, usually as a direct replacement for JSP. Some of the benefits of using Velocity to generate web pages are: + ++ **Simplicity** - The pages can be written and maintained by non-technical web designers. ++ **Ease of maintainance** - Scripting is removed from web pages with the recommended MVC approach. ++ **Access both methods and properties** - Web designers can reference methods as well as properties of objects in a context. ++ **Consistency** - Velocity can be used for other text generation tasks (such as sending email) +providing a consistent way to mark up text. + +This document provides some basic info on getting started with Velocity in a web application. + +## Use a Famework + +The primary purpose of the Velocity engine is simply to generate text based on a template. Consequently, Velocity does not contain any web-related functionality in and of itself. To make a web application, you will need a framework to respond to HTTP requests, handle user authentication, make business logic calls, and generate a response. There are several strong contenders. + +1. **Velocity Tools / VelocityViewServlet** - The easiest way to get started is to download the companion <a href="http://velocity.apache.org/tools/devel/" class="externalLink">Velocity Tools</a> subproject and use the [VelocityViewServlet](http://velocity.apache.org/tools/devel/view/). This servlet is easy to configure and install. You create a directory of templates on your web server, optionally edit an XML file that lists various "Tools" to place in the context and you are off. More details can be found in the tutorial below. +2. **Velocity Tools / VelocityStruts** - You may be familiar with the popular <a href="http://struts.apache.org/" class="externalLink">Struts</a> framework, originally designed to provide much needed application functionality to JSP. With the [VelocityStruts](http://velocity.apache.org/tools/devel/struts/) module of Velocity Tools you can substitute Velocity for JSP as the page template language. This allows you to take advantage of the large base of Struts infrastructure while designing pages using Velocity. +3. **Third party frameworks** - There are a number of third party frameworks listed on the [PoweredByVelocity](http://wiki.apache.org/velocity/PoweredByVelocity) wiki page. Of these, [Spring](http://www.springframework.org/) is probably the most sophisticated and well known. [Turbine](http://turbine.apache.org/) has many features and can also be very useful. It was built with Velocity as the primary page language, which is not surprising since many of the original Velocity developers were involved in creating it. Simpler alternatives are the [Click](http://click.sourceforge.net/) or [Maverick](http://mav.sourceforge.net/) frameworks, which provide a simple Controller architecture that integrates nicely with Velocity. +4. **Build your own** - A final alternative is to build your own framework. Create a dispatcher servlet, retrieve templates from a file or database, integate with your business logic and send the results back to the user. Often you'll have an easier time starting with one of the existing frameworks and customizing it. In particular you can add new functionality to the VelocityViewServlet simply by creating a subclass. + +As a side note, you may also come across references to VelocityServlet, which is a deprecated servlet that was included in the Velocity Engine up to version 1.4. Since VelocityServlet is no longer being maintained we strongly recommend you use VelocityViewServlet in Velocity Tools instead. + +## Web-Specific Issues + +There are a few issues with Velocity that are specific to web applications. Here is a brief discussion of the most commonly encountered issues. + +### Resource Loading Headaches + +The default Velocity Engine settings make use of the FileResourceLoader. This is great for most applications that are not deployed to a servlet engine. Once you need to build a web application and ship or deploy it as a WAR file, the FileResourceLoader can become your worst enemy. So, we explicitly recommend you do NOT use the FileResourceLoader for your web applications. + +Really, any of the other ResourceLoader implementations out there are preferred, but all the other ResourceLoaders shipped with Velocity Engine will require you to store your templates somewhere besides the standard file system (e.g. in the classpath, in a database, or on a remote server). If that works for you, then great! However, we recognize that these are not convenient for most people's development cycle. + +The simplest replacement for FileResourceLoader in a web application is actually a part of the VelocityTools project. It is the [WebappResourceLoader](/tools/devel/apidocs/org/apache/velocity/tools/view/WebappResourceLoader.html) This ResourceLoader implementation is specifically designed to work just like the FileResourceLoader, but it is aware of the servlet context and allows you to configure resource paths relative to the servlet root, rather than the local file system. + +If you are using the VelocityViewServlet, then it is automatically configured and ready to use the WebappResourceLoader. So if you want to change the configured path(s), you need only add a line like the following to your velocity.properties: + + :::properties + webapp.resource.loader.path=/WEB-INF/mytemplates/ + +If you need to set the WebappResourceLoader up on your own, then you can make your properties something like this: + + :::properties + resource.loader=webapp + webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader + webapp.resource.loader.path=/WEB-INF/mytemplates/ + +You will **also need to put the ServletContext into your VelocityEngine's application attributes** before initializing that Engine. This is how the WebappResourceLoader knows how to find templates. + + :::java + myVelocityEngine.setApplicationAttribute("javax.servlet.ServletContext", servletContext); + +### Changing Object State - Don't! + +Velocity provides the ability to call any method of an object acting as a reference. This can be useful when displaying information into the page but is dangerous when object or application state is modified. + +For example, the following code safely calls the size() method of a list and displays the result. + + :::velocity + There are $users.size() currently logged in. + +An example of an unsafe operation concerns a financial web page with an object in the context that calculates data year by year. The method calculateNextYear() calculates data for the next year and advances an internal counter: + + :::velocity + 2005 data: $table.data + $table.calculateNextYear() + 2006 data: $table.data + +The problem with this approach is that the code cannot be repeated in multiple parts of the page. You may not intend to do so, but it's easy to forget this when cutting and pasting or writing control statements (such as #if or #foreach). This becomes more of an issue when you are dealing with application or session-level state. + +The (strongly) recommended practice is to only use Velocity for inserting information into text. Method calls can be useful to retrieve information. However, it's generally a bad idea to use a method call to change object state, and it's always a bad idea to change application state. + +If you find yourself needing to change object state (as in the previous example) try precalculating all the possible values in the controller and putting them in a List or Map. Any changes to application state should always be done by the controller. + +On a related note, you should always put a List or Set into the context instead of an Iterator or Enumeration. This allows the collection to be used more than once in the page with no change in behavior. + +### Escaping HTML/XML Entities + +Any user-entered text that contains special HTML or XML entities (such as <, >, or &) needs to be escaped before included in the web page. This is required, both to ensure the text is visible, and also to prevent dangerous [cross-site scripting](http://en.wikipedia.org/wiki/Cross_site_scripting). Unlike, for example, JSTL (the Java Standard Tag Language found in Java Server Pages), Velocity does not escape references by default. + +However, Velocity provides the ability to specify a `ReferenceInsertionEventHandler` which will alter the value of a reference before it is inserted into the page. Specifically, you can configure the `EscapeHtmlReference` handler into your `velocity.properties` file to escape all references (optionally) matching a regular expression. The following example will escape HTML entities in any reference that starts with "msg" (e.g. `$msgText`). + + :::properties + eventhandler.referenceinsertion.class = org.apache.velocity.app.event.implement.EscapeHtmlReference + eventhandler.escape.html.match = /msg.*/ + +Note that other kinds of escaping are sometimes required. For example, in style sheets the @ character needs to be escaped, and in Javascript strings the single apostrophe ' needs to be escaped. + +### Securing the Application + +Since a web application is running on a central server, that typically has multiple users and confidential resources, care must be taken to make certain that the web application is secure. Most standard web security principles apply to a web application built with Velocity. A few specific issues (such as system configuration, more on cross-site scripting, and method introspection) are written up in this article on [Building Secure Applications with Velocity](http://wiki.apache.org/velocity/BuildingSecureWebApplications). In particular, you may want to prevent template designers from including "dangerous" reflection-related methods by specifying the `SecureUberspector` to get/set properties and execute method calls. + + :::properties + runtime.introspector.uberspect = org.apache.velocity.util.introspection.SecureUberspector + +### Logging + +Since Velocity logging uses the SLF4J logging facade, you will need to provide an SLF4J binding. Check the [dependecies](#dependencies) section in the developer guide for a list of SLF4J bindings. + +## Tutorial + +What follows is a brief tutorial on building a simple web app with VelocityViewServlet. Note that it suggests you compile VelocityViewServlet from the source. This isn't actually required to use VelocityViewServlet but we recommend it in this case in order to see the source and then compile the example files. + +Prerequisites for doing the following include the Java Developer's Kit (JDK) and [Apache Ant](http://ant.apache.org/). + +For more information, consult the [Velocity Tools](http://velocity.apache.org/tools/devel/) documentation. + +1. Download the Velocity Tools project source (you need the source for the examples) from the [download page](http://velocity.apache.org/download.cgi#tools). + +2. Build the Velocity Tools jar and the "simple" example by typing: + + :::shell + ant example.simple + +3.Take a look at the "examples" directory. You will see a file "index.vm". Here's an excerpt: + + :::html+velocity + <html> + <body> + I'm a velocity template. + + #if( $XHTML ) + #set( $br = "<br />" ) + #else + #set( $br = "<br>" ) + #end + + $br + $br + + Here we use a custom tool: $toytool.message + + $br + $br + + Here we get the date from the DateTool: $date.medium + </body> + </html> + +You can copy any additional velocity files into this same directory. In `examples/WEB-INF` you will see a file "tools.xml". This specifies a list of "Tools" that are automatically included in the context. + + :::xml + <tools> + <data type="boolean" key="xhtml" value="true"/> + <data type="boolean" key="isSimple" value="true"/> + <data type="number" key="version" value="2.0"/> + <data key="foo">this is foo</data> + <data key="bar">this is bar.</data> + <toolbox scope="request"> + <tool key="toytool" class="ToyTool" restrictTo="index*"/> + </toolbox> + <toolbox scope="session"> + <tool key="map" class="java.util.HashMap"/> + </toolbox> + </tools> + +And finally the web.xml file specifies the name of the servlet and location of toolbox.properties. + + :::xml + <web-app> + <servlet> + <servlet-name>velocity</servlet-name> + <servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class> + </servlet> + <servlet-mapping> + <servlet-name>velocity</servlet-name> + <url-pattern>*.vm</url-pattern> + </servlet-mapping> + <welcome-file-list> + <welcome-file>index.vm</welcome-file> + </welcome-file-list> + </web-app> + +4. Copy this directory into your "webapps" directory on Tomcat. You could also copy "simple.war", but copying in the entire directory will let you experiment with changes. You should now be able to access your simple one-page webapp with this URL. (or something similar): + + http://localhost:8080/simple/index.vm + +5. Experiment with adding new Velocity pages. Note that you can access any velocity page just by changing the URL. Try changing the entries in tools.xml or creating your own tools. Consult the <a href="http://velocity.apache.org/tools/devel/" class="externalLink">Velocity Tools</a> documentation, the "showcase" example application, and the [Wiki](http://wiki.apache.org/velocity/) for more info on the wide variety of tools available.
