<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<!--
 Copyright 2006 The Apache Software Foundation.

 Licensed under the Apache License, Version 2.0 (the "License")
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<book lang="en">
  <title>Velocity Users Guide</title>

  <bookinfo>
    <copyright>
      <year>2006</year>

      <holder>The Apache Software Foundation</holder>
    </copyright>

    <releaseinfo>Version 1.5</releaseinfo>

    <productname>Velocity</productname>

    <authorgroup>
      <corpauthor>The Apache Velocity Developers</corpauthor>
    </authorgroup>

    <mediaobject>
      <imageobject>
        <imagedata fileref="images/logo.png"/>
      </imageobject>
    </mediaobject>
  </bookinfo>

  <toc/>

  <chapter id="chapter-preface">
    <title>Preface</title>

    <section id="section-about-this-guide">
      <title>About this Guide</title>

      <para>The Velocity Users Guide is intended to help page designers and
      content providers get acquainted with Velocity and the syntax of its
      simple yet powerful scripting language, the Velocity Template Language
      (VTL). Many of the examples in this guide deal with using Velocity to
      embed dynamic content in web sites, but all examples are equally
      applicable to other pages and templates.</para>

      <para><emphasis role="bold">Thanks for choosing
      Velocity!</emphasis></para>
    </section>

    <section id="section-acknowledgements">
      <title>Acknowledgements</title>

      <para>This guide has been compiled from the xdoc Version which was
      included with Velocity up to version 1.4. We explicitly acknowledge the
      efforts of all the contributors, especially Jason Van Zyl and John
      Castura in preparing this first version.</para>
    </section>

    <section id="section-audience">
      <title>Intended Audience</title>

      <para>This guide is for you if you want to learn how to use the Velocity
      Templating Language (VTL). It is intended for designers, template
      writers and developers that are familiar with creating content templates
      or web pages. If you want to embed the Velocity engine into your own
      application, you probably want to consult the Velocity Developers Guide
      available from <uri>http://velocity.apache.org/</uri> and use this guide
      as a reference.</para>
    </section>

    <section id="section-feedback">
      <title>Feedback</title>

      <para>If you encounter any mistakes in this manual or have other
      feedback related to the Velocity Users Guide, please send email to one
      of the Velocity mailing lists:</para>

      <variablelist>
        <varlistentry>
          <term><email>user@velocity.apache.org</email></term>

          <listitem>
            <para>This mailing list is intended for discussion about using
            Velocity, e.g. writing templates or integrating Velocity into your
            application. If you need clarification about the content of this
            guide or have questions about the examples, please send them to
            this list.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term><email>dev@velocity.apache.org</email></term>

          <listitem>
            <para>This mailing list is intended for discussion about
            developing Velocity itself. If you found a mistake in this guide,
            want to improve its contents or the formatting framework, please
            use this mailing list.</para>
          </listitem>
        </varlistentry>
      </variablelist>

      <para>Please check also the Velocity Homepage located at
      <uri>http://velocity.apache.org/</uri> for up-to-date information, new
      releases and general Velocity information.</para>
    </section>
  </chapter>

  <chapter id="chapter-what-is-velocity">
    <title>What is Velocity?</title>

    <para>The Apache Velocity templating engine (or short
    <firstterm>Velocity</firstterm> is a template engine written in 100% pure
    Java. It permits web page designers to reference methods defined in Java
    code. Template developers can work in parallel with Java programmers to
    develop web sites according to the Model-View-Controller (MVC) model,
    meaning that they can focus solely on creating templates, and programmers
    can focus solely on writing Java code. Velocity separates Java code from
    the template pages, making a project more maintainable over the long
    run.</para>

    <para>In a web context, Velocity provides a viable alternative to Java
    Server Pages (JSPs) or PHP.</para>

    <para>Velocity can be used to generate web pages, Java source code, SQL,
    PostScript and other output from <firstterm>templates</firstterm>. It can
    be used either as a standalone utility for generating source code and
    reports, or as a component integrated into frameworks or larger
    applications.</para>

    <para>Velocity provides template services for a number of other projects,
    e.g. the Turbine web application framework
    (<uri>http://jakarta.apache.org/turbine/</uri>). In this context, Velocity
    offers a template service that allows development of web applications
    according to a true MVC model.</para>

    <section id="section-the-fruit-store">
      <title>The Fruit Store</title>

      <para>Suppose you are a page designer for an online store that
      specializes in selling fruits. Let's call it <emphasis>The Online Fruit
      Store</emphasis>. Customers place orders for various types and
      quantities of fruits. They login to your site using their username and
      password, which allows them to view their orders and buy more fruits.
      Right now, apples on sale, which are very popular. A minority of your
      customers regularly buy mangos, which are also on sale, though not as
      popular and usually relegated to the margin of your web page.
      Information about each customer is tracked in a database, so one day the
      question arises: <emphasis>Why not use Velocity to target special deals
      on fruit to the customers who are most interested in those types of
      fruits?</emphasis></para>

      <para>Velocity makes it easy to customize web pages to your online
      visitors. As a web site designer at <emphasis>The Online Fruit
      Store</emphasis>, you will modify the web page that the customer sees
      after logging into your site.</para>

      <para>You meet with software engineers at your company, and everyone has
      agreed that <literal>$customer</literal> will hold information
      pertaining to the customer currently logged in and that
      <literal>$fruitSpecial</literal> will be all the types of fruit on sale
      at present. The <literal>$promoTool</literal> object contains methods
      that help with promotion.</para>

      <para>For the task at hand, let's concern ourselves only with these
      three references. Remember, you don't need to worry about how the
      software engineers extract the necessary information from the database,
      you just need to know that it works. This lets you get on with your job,
      and lets the software engineers get on with theirs.</para>

      <para>The next example shows how to display promotions using
      Velocity.</para>

      <example id="example-displaying-the-promotions-for-the-fruit-store">
        <title>Displaying the promotions for the Fruit Store</title>

        <programlisting>&lt;html&gt;
  &lt;body&gt;
Hello $customer.Name!
    &lt;table&gt;
      #foreach( $fruit in $fruitSpecial )
        #if ( $customer.hasPurchased($fruit) )
          &lt;tr&gt;
            &lt;td&gt;
              $promoTool.getPromo($fruit)
            &lt;/td&gt;
          &lt;/tr&gt;
        #end
      #end
    &lt;/table&gt;
  &lt;/body&gt;
&lt;/html&gt;</programlisting>
      </example>

      <para>The exact details of the <literal>#foreach</literal> and
      <literal>#if</literal> directive will be described in greater depth in
      the <link linkend="chapter-directives">directives chapter</link>; what is
      important is the impact this short piece of code has on your web site.
      When a customer with a penchant for mangos logs in, and mangos are on
      sale, that is what this customer will see, prominently displayed. If
      another customer with a long history of apple purchases logs in, the
      notice of an apple sale will be front and center. The flexibility of
      Velocity is enormous and limited only by your creativity.</para>

      <para>This manual should help you get started with Velocity and the
      Velocity Template Language. It has a companion manual, the
      <firstterm>Velocity Developers Guide</firstterm>, which describes how to
      integrate Velocity into your own web applications (this is what the
      software engineers at your company want to read).</para>
    </section>

    <section id="section-velocity-template-language-introduction">
      <title>An introduction to the Velocity Template Language</title>

      <para>The <firstterm>Velocity Template Language</firstterm>
      (<firstterm>VTL</firstterm>) is meant to provide an easy, simple and
      clean way to incorporate dynamic content in a web page. Even a web page
      developer with little or no programming experience will soon be capable
      of using VTL to incorporate dynamic content in a web site.</para>

      <para>VTL uses <firstterm>references</firstterm> to embed dynamic
      content in a web site, and a variable is one type of reference. They can
      refer to something defined in the Java code, or it can get its value
      from a VTL <firstterm>statement</firstterm> in the web page
      itself.</para>

      <example id="example-simple-vtl-statement">
        <title>A simple VTL statement</title>

        <programlisting>#set( $a = "Velocity" )</programlisting>
      </example>

      <para>This VTL statement begins with the <literal>#</literal> character
      and contains a <firstterm>directive</firstterm>: <literal>set</literal>.
      When an online visitor requests your web page, Velocity will search
      through your web page to find all <literal>#</literal> characters, then
      determine which mark the beginning of VTL statements, and which of the
      <literal>#</literal> characters that have nothing to do with VTL.</para>

      <para>The <literal>#</literal> character is followed by a directive,
      <literal>set</literal>. The <literal>set</literal> directive uses an
      expression (enclosed in brackets) -- an equation that assigns a value to
      a reference. The reference is listed on the left hand side and its value
      on the right hand side; the two are separated by an <literal>=</literal>
      character.</para>

      <para>In the example above, the reference is <literal>$a</literal> and
      the value is <literal>Velocity</literal>. A reference always begins with
      the <literal>$</literal> character.</para>

      <para>The value on the right side represents a string value. These are
      always enclosed in quotes, either single or double quotes. Single quotes
      will ensure that the quoted value will be assigned to the reference
      <emphasis>as is</emphasis>. Double quotes allow you to use Velocity
      references ot interpolate, such as <literal>"Hello $name"</literal>,
      where the <literal>$name</literal> will be replaced by its current value
      before that string literal is assigned to the left hand side of the
      <literal>=</literal>.</para>

      <para>The following rule of thumb may be useful to better understand how
      Velocity works: References begin with <literal>$</literal> and are used
      to get something. Directives begin with <literal>#</literal> and are
      used to do something.</para>

      <para>In the example above, <literal>#set</literal> is used to assign a
      value to a reference. The reference, <literal>$a</literal>, can then be
      used in the template to output <literal>Velocity</literal>.</para>
    </section>

    <section id="section-hello-velocity-world">
      <title>Hello Velocity World!</title>

      <para>Once a value has been assigned to a reference, you can use it
      anywhere in your HTML document. In the following example, a value is
      assigned to <literal>$name</literal> and later referenced.</para>

      <example id="example-hello-velocity-world">
        <title>"Hello World" using Velocity</title>

        <programlisting>&lt;html&gt;&lt;body&gt;
#set( $name = "Velocity" )
Hello $name World!
&lt;/body&gt;&lt;/html&gt;</programlisting>
      </example>

      <para>The result is a web page that reads</para>

      <programlisting>Hello Velocity World!</programlisting>

      <para>To make statements containing VTL directives more readable, we
      encourage you to start each VTL statement on a new line, although you
      are not required to do so.</para>
    </section>
  </chapter>

  <chapter id="chapter-language-elements">
    <title>Language elements</title>

    <para>Like other formal languages, Velocity consists of a number of
    elements:</para>

    <itemizedlist>
      <listitem>
        <para><link linkend="section-directives">Statements and
        Directives</link></para>
      </listitem>

      <listitem>
        <para><link linkend="section-reference">References</link></para>
      </listitem>

      <listitem>
        <para><link linkend="section-comments">Comments</link></para>
      </listitem>
    </itemizedlist>

    <para>Each of these elements will be introduced in this chapter.</para>

    <section id="section-directives">
      <title>Statements and directives</title>

      <para>Velocity directives are language elements than allow the template
      designer to manipulate the rendering of the template. A directive is
      part of a Velocity statement:</para>

      <programlisting>## Velocity single-line statement
#<co id="co-statement-hash" linkends="ca-statement-hash"/>set<co
          id="co-statement-directive" linkends="ca-statement-directive"/>($a = 10)<co
          id="co-statement-expression" linkends="ca-statement-expression"/>

## Velocity multi-line statement
#<co id="co-statement-hash2" linkends="ca-statement-hash"/>foreach<co
          id="co-statement-directive2" linkends="ca-statement-directive"/>($i in [0..10])<co
          id="co-statement-expression2" linkends="ca-statement-expression"/>
  Counter is $i <co id="co-statement-body" linkends="ca-statement-body"/>
#end<co id="co-statement-end" linkends="ca-statement-end"/></programlisting>

      <calloutlist>
        <callout arearefs="co-statement-hash co-statement-hash2"
                 id="ca-statement-hash">
          <para>Begin of Velocity statement (hash symbol)</para>
        </callout>

        <callout arearefs="co-statement-directive co-statement-directive2"
                 id="ca-statement-directive">
          <para>Velocity directive</para>
        </callout>

        <callout arearefs="co-statement-expression co-statement-expression2"
                 id="ca-statement-expression">
          <para>Expression in brackets</para>
        </callout>

        <callout arearefs="co-statement-body" id="ca-statement-body">
          <para>Multi-line statement body</para>
        </callout>

        <callout arearefs="co-statement-end" id="ca-statement-end">
          <para>Multi-line statement end</para>
        </callout>
      </calloutlist>

      <para>Velocity knows about <firstterm>single-line statements</firstterm>
      and <firstterm>multi-line statements</firstterm>.</para>

      <para>A single-line statement starts with a single <literal>#</literal>
      character, followed by directive itself. Some directives also take
      parameters in brackets. A single-line statement then ends
      immediately.</para>

      <example id="example-velocity-single-line-statements">
        <title>Velocity single-line statements</title>

        <programlisting>#set($name = "apple")

#include("header.html")

#parse("header.vm")

#stop</programlisting>
      </example>

      <para>A multi-line statement starts like a single-line statement, but
      also has a statement body. This body ends with
      <literal>#end</literal><footnote>
          <para>Technically speaking, the opening statement and
          <literal>#end</literal> can be on the same line. We will still call
          it a multi-line statement.</para>
        </footnote>.</para>

      <example id="example-velocity-multi-line-statements">
        <title>Velocity multi-line statements</title>

        <programlisting>#foreach($i in [1..10])
  The count is $i
#end

#literal
 This is a literal block of text
#end

#if ($fruit == "apple")
  This is an apple.
#else
  This is not an apple.
#end</programlisting>
      </example>

      <note>
        <para>The
        <literal>#if</literal>/<literal>#else</literal>/<literal>#end</literal>
        combo is a special case because it might contain multiple statement
        bodies between its elements.</para>
      </note>

      <para>If you need to explicitly separate a Velocity directive from
      surrounding text, it is possible to wrap it in curly braces
      (<literal>{</literal> and <literal>}</literal>):</para>

      <example id="example-formal-directives">
        <title>Velocity directives in formal notation</title>

        <programlisting>#{set}($name = "apple")

#{foreach}($i in [1..10])
 The count is $i
#{end}</programlisting>
      </example>

      <para>All available Velocity directives are listed in the <link
      linkend="chapter-directives">directives chapter</link>.</para>

      <note>
        <para>While the hash sign is technically not part of the directive, we
        will still speak about the <literal>#if</literal> or
        <literal>#set</literal> directive in the latter chapters.</para>
      </note>
    </section>

    <section id="section-reference">
      <title>References</title>

      <para>Velocity references are the glue which connect templates to the
      application. Template designers and application developers must agree on
      a common set of references used by the Java application and the Velocity
      templates. Every Velocity reference represents a Java object.</para>

      <para>A Velocity reference starts with a <literal>$</literal> character
      followed by an <firstterm>identifier</firstterm> name.</para>

      <example id="example-velocity-references">
        <title>Velocity references</title>

        <programlisting>## Simple reference
The total amout is $total.

## Property reference
You currently have $cart.items Items in your Shopping cart.

## Method reference
We offer you a discount of $cart.calculateDiscount() for your purchase.

## Creating a new reference from Velocity
#set($linesPerPage = 20)</programlisting>
      </example>

      <para>If you need to separate a reference identifier name from the
      surrounding template, you can wrap the reference identifier in curly
      braces (<literal>{</literal> and <literal>}</literal>):</para>

      <example id="example-formal-velocity-references">
        <title>Formal velocity references</title>

        <programlisting>The total amout is ${total}.

You currently have ${cart.items} Items in your Shopping cart.</programlisting>
      </example>

      <para>Velocity references are discussed in depth in the <link
      linkend="chapter-references">references chapter</link>.</para>
    </section>

    <section id="section-comments">
      <title>Comments</title>

      <para>Comments allow descriptive text to be included in a template that
      is not placed into the output of the template engine. Comments are a
      useful way of reminding yourself and explaining to others what your VTL
      code is doing, or any other purpose you find useful.</para>

      <para>Like the Java programming language, Velocity has single-line and
      block comments.</para>

      <para>A single-line comment begins with <literal>##</literal> and
      finishes at the end of the line.</para>

      <example id="example-vtl-single-line-comments">
        <title>Single-line comments</title>

        <programlisting>## This is a single-line comment.

This is visible in the output ## This is a comment.</programlisting>
      </example>

      <para>If you are going to write a few lines of commentary, there is no
      need to have numerous single-line comments. Multi-line comments, which
      begin with <literal>#*</literal> and end with <literal>*#</literal>, are
      available to handle this scenario:</para>

      <example id="example-multi-line-comment">
        <title>A multi-line comment</title>

        <programlisting>This is text that is outside the multi-line comment.
Online visitors can see it.

#*
  Thus begins a multi-line comment. Online visitors will not
  see this text because the Velocity templating engine will
  ignore it.
*#

Here is text outside the multi-line comment; it is visible.</programlisting>
      </example>

      <para>Multi-line comments can start and end in arbitrary columns of the
      template.</para>

      <para>There is a third type of comment, the VTL <firstterm>comment
      block</firstterm>, which may be used to store such information as the
      document author and versioning information. It is similar to the Javadoc
      comment block in the Java programming language and starts with
      <literal>#**</literal>.</para>

      <example id="example-vtl-comment-block">
        <title>A VTL comment block</title>

        <programlisting>#**
This is a VTL comment block and
may be used to store such information
as the document author and versioning
information:
@author
@version 5
*#</programlisting>
      </example>
    </section>

    <?hard-pagebreak ?>

    <section id="section-escaping-vtl-elements">
      <title>Escaping VTL elements</title>

      <para>Most of the time, there is no problem, rendering a Velocity
      template because the rendering engine is quite smart about finding
      Velocity statements and references and distinguishing them from regular
      text.</para>

      <example id="example-distinguishing-between-text-and-references">
        <title>Distinguishing between text and references</title>

        <programlisting>## Renders as normal text, because the dollar sign 
## is not followed by a letter.
I bought a 4 lb. sack of potatoes for only $2.50!

## Renders as variable
I bought a 4 lb. sack of potatoes for only $money.</programlisting>
      </example>

      <para>Velocity allows for explicit escaping of references and directives
      using the <literal><literal>\</literal></literal> (backslash) character.
      If the character following the <literal>\</literal> would start a new
      directive or reference, then this character is output verbatim. This can
      lead to some unexpected behaviour, especially with directives.</para>

      <example id="example-vtl-escaping-examples">
        <title>VTL escaping examples</title>

        <programlisting>\         ## Renders as a single backslash (no # or $ follows)

\\ \# \$  ## Renders as \\ \# \$ (no directive or reference follows)

\#end     ## Renders as #end, backslash escapes an existing directive</programlisting>
      </example>

      <para>Unfortunately, the escaping of VTL elements contains a number of
      quirks that make them actually hard to use<footnote>
          <para>It is really mind-boggling how we came up with this. It is
          tied more to the internal workings of the Velocity engine than any
          user-friendlyness. This is definitely subject to change in future
          Velocity versions. Until then, please be kind to our
          mistakes.</para>
        </footnote>. As you have seen, the behaviour of the
      <literal>\</literal> differs whether a directive or just text
      follows:</para>

      <example id="example-escaping-vtl-references">
        <title>Escaping VTL references</title>

        <programlisting>$a     ## $a is a reference but an unbound one (it has no value)
       ## This renders as $a in the output

\$a    ## Escaping an unbound reference renders it as \$a

#set($a = 10)  ## When a value is assigned to the reference...

$a     ## ... then it renders as 10 ...

\$a    ## ... and gets escaped and now renders as $a.</programlisting>
      </example>

      <?hard-pagebreak ?>

      <para>Escaping VTL statements works in the same way.</para>

      <example id="example-escaping-vtl-statements">
        <title>Escaping VTL statements</title>

        <programlisting>\#end    ## Renders as #end
\# end   ## Renders as \# end (note the space)

\#set ($a = 10) ## Renders as #set ($a = 10)

## If $a has been assigned a value:

#set ($a = 10)
\#set ($a = 20) ## Renders as #set (10 = 20)

## The backslash does not escape a whole multi-line statement
## This is a syntax error: (#end without a starting statement)
\#if ($a == 10)
#end</programlisting>
      </example>

      <para>Using <link linkend="chapter-velocity-macros">Velocity
      Macros</link>, the behaviour of escaping <literal>#</literal> changes a
      bit:<footnote>
          <para>...and you probably thought, the worst part was over...</para>
        </footnote></para>

      <example id="example-escaping-velocimacros">
        <title>Escaping Velocimacros</title>

        <programlisting>#apple    ## Renders as #apple, because it is not a VTL
          ## statement
\#apple   ## Renders as \#apple

#macro(apple)
 Apple
#end

#apple    ## This is now a syntax error
          ## (#apple Velocimacro invocation needs brackets)

#apple()  ## Renders as Apple (invocation of a Velocimacro)

\#apple   ## renders as #apple, because it is now a VTL
          ## statement after Velocimacro definition.</programlisting>
      </example>
    </section>
  </chapter>

  <chapter id="chapter-references">
    <title>References</title>

    <para>There are three types of references in the VTL:
    <firstterm>variables</firstterm>, <firstterm>properties</firstterm> and
    <firstterm>methods</firstterm>. They are the glue that connects the
    business logic of your application written in Java to your templates. The
    Java code and the templates must use the same set of references, so you as
    a template designer and the developers writing the application logic must
    agree on the references available for use on the templates.</para>

    <para>Every reference that is output when a template is rendered, is
    converted to a Java string by calling the <literal>toString()</literal>
    method on the Java object which represents the reference. If you want a
    reference rendered in a special way, you can ask your Java developers to
    implement or override this method.</para>

    <section id="section-identifiers">
      <title>Identifiers</title>

      <para>All references consist of a leading <literal>$</literal> character
      followed by a VTL identifier. A VTL identifier must start with an
      alphabetic character (a..z or A..Z). The rest of the characters are
      limited to the following types of characters:</para>

      <para><itemizedlist spacing="compact">
          <listitem>
            <para>alphabetic (<literal>a..z</literal>,
            <literal>A..Z</literal>)</para>
          </listitem>

          <listitem>
            <para>numeric (<literal>0..9</literal>)</para>
          </listitem>

          <listitem>
            <para>hyphen and underscore (<literal>-</literal> and
            <literal>_</literal>)</para>
          </listitem>
        </itemizedlist></para>

      <para>Velocity identifiers are, just as Java variable names,
      <emphasis>case-sensitive</emphasis>.</para>
    </section>

    <section id="section-variables">
      <title>Variables</title>

      <para>Variables are the simplest type of references, because each
      reference is also a variable. Each variable represents a Java
      object.</para>

      <example id="example-valid-variable-names">
        <title>Valid variable names</title>

        <programlisting>$foo
$bar
$foo-bar
$foo_bar
$fooBar1</programlisting>
      </example>

      <para>Velocity keeps an internal map from identifiers to variables
      called the <firstterm>context</firstterm>. The is the place where Java
      code can put objects to be referenced from the template.</para>

      <para>A variable must be assigned a value before it can be referenced
      from the template. Assigning a value to a Velocity variable is the same
      as placing an object in the context from the Java code of your
      application.</para>

      <example id="example-creating-a-context-object">
        <title>Creating a new context object</title>

        <programlisting>## Puts a String object representing "bar" in the context
#set( $foo = "bar" )</programlisting>
      </example>

      <note>
        <para>Assigning a new value using the #set statement to a variable
        does change the object present in the context.</para>
      </note>
    </section>

    <section id="section-properties">
      <title>Properties</title>

      <para>Velocity allows you to access properties through a short-hand
      notation. The objects to look up the properties must be available
      through a Velocity variable and the notation consists of a leading
      variable followed by the dot ("<literal>.</literal>") character and
      another VTL identifier.</para>

      <example id="example-valid-property-names">
        <title>Valid property names</title>

        <programlisting>$customer.address
$purchase.total
$cart.customerDiscount</programlisting>
      </example>

      <para>A property name can represent the following elements depending on
      the object used for look-up:</para>

      <para><itemizedlist spacing="compact">
        <listitem>
          <para>If the object has a method
          <literal>get&lt;property&gt;</literal> where the property name is
          not modified, this method is invoked</para>
        </listitem>

        <listitem>
          <para>else if the object is a Java bean (has methods conforming to
          the Sun Java Bean specification for accessing bean properties), the
          bean getter is executed to access the value</para>
        </listitem>

        <listitem>
          <para>finally if the object used to look up the property has a
          <literal>get(String)</literal> method, invoke this method.</para>
        </listitem>
      </itemizedlist></para>

      <para>Take the first example, <literal>$customer.address</literal>. It
      can have multiple meanings:<footnote>
          <para>The sequence of these lookups is determined by the Velocity
          <firstterm>Uberspector</firstterm>. This is merely the default
          lookup. A Java developer can customize this behaviour by using a
          custom Uberspector.</para>
        </footnote></para>

      <para><itemizedlist spacing="compact">
        <listitem>
          <para>when the object has a method <literal>getaddress()</literal>,
          invoke this method</para>
        </listitem>

        <listitem>
          <para>when the object is a Java bean with a property
          <literal>address</literal>, invoke its getter,
          <literal>getAddress()</literal></para>
        </listitem>

        <listitem>
          <para>when the object has a method <literal>get(String)</literal>,
          invoke this method, passing <literal>address</literal> as
          parameter.</para>
        </listitem>

        <listitem>
          <para>when the object has a method <literal>isAddress()</literal>,
          invoke this method.</para>
        </listitem>
      </itemizedlist></para>

      <note>
        <para>When a property name refers to a getter method,
        <literal>$obj.property</literal> and <literal>$obj.Property</literal>
        will both invoke the same method (either
        <literal>getproperty()</literal> or <literal>getProperty()</literal>).
        However, if the object represented by <literal>$obj</literal> has a
        <literal>get(String)</literal> method,
        <literal>$obj.property</literal> and <literal>$obj.Property</literal>
        will pass different values to this <literal>get(String)</literal>
        method. This can lead to hard-to-find problems.</para></note>

       <para>It is a good practice
        to standardize the capitalization of property names in your
        application<footnote>
            <para>While lots of the available Velocity literature uses
            upper-case capitalization, it is actually a good idea to use
            lower-case capitalization as this is consistent with JSTL and the regular
            bean property notation.</para>
          </footnote>.</para>

      <para>If you wonder about setting property values, please look up the
      <literal>#set()</literal> directive chapter. The setting of properties
      is discussed there.</para>

      <section id="section-default-property-lookup-rules">
        <title>Default property lookup rules</title>

        <para>Velocity is quite clever when figuring out which method
        corresponds to a requested property<footnote>
            <para>Some people would say that it is entirely too clever.</para>
          </footnote>. It tries out different alternatives based on several
        established naming conventions. The exact lookup sequence depends on
        whether or not the property name starts with an upper-case letter. For
        lower-case names, such as <literal>$customer.address</literal>, the
        sequence is:</para> <para><itemizedlist spacing="compact">
            <listitem>
              <para><literal>getaddress()</literal></para>
            </listitem>

            <listitem>
              <para><literal>getAddress()</literal></para>
            </listitem>

            <listitem>
              <para><literal>get("address")</literal></para>
            </listitem>

            <listitem>
              <para><literal>isAddress()</literal></para>
            </listitem>
          </itemizedlist></para>

        <para>For upper-case property names like
        <literal>$customer.Address</literal>, it is slightly different:</para>
        <para><itemizedlist spacing="compact">
            <listitem>
              <para><literal>getAddress()</literal></para>
            </listitem>

            <listitem>
              <para><literal>getaddress()</literal></para>
            </listitem>

            <listitem>
              <para><literal>get("Address")</literal></para>
            </listitem>

            <listitem>
              <para><literal>isAddress()</literal></para>
            </listitem>
          </itemizedlist></para>

        <para>As regular bean properties tend to be written in lowercase
        notation, you should talk to your programmers that they don't add both
        lower-case and upper-case methods to their objects. It would be a bad
        idea anyway.</para>

        <caution>
          <para>There are some exotic naming cases, such as a property
          starting with multiple upper-case letters which are treated
          specially according to the Java Bean specification. Velocity does
          not conform to this specification to the last letter, so if you have
          a method called <literal>getURL()</literal>, you cannot use
          <literal>$obj.url</literal> to invoke the method, you must use
          <literal>$obj.URL</literal> or <literal>$obj.uRL</literal>. This
          might change in future versions of Velocity.</para>
        </caution>
      </section>
    </section>

      <?hard-pagebreak ?>

    <section id="section-methods">
      <title>Methods</title>

      <para>A method is part of a context object, written in Java code, and is
      capable of doing something useful, like running a calculation or
      arriving at a decision. Method invocation is indicated by round
      parentheses following the method name. These parentheses can optionally
      contain a parameter list.</para>

      <example id="example-valid-method-references">
        <title>Valid method references</title>

        <programlisting>$cart.calculateTotal()
$customer.updatePurchases($cart)
$shop.checkInventory()
$cart.addTaxes(8, 16)

# Property access
$page.setTitle( "My Home Page" )
$customer.getAddress()
$purchase.getTotal()</programlisting>
      </example>

      <para>The last few examples are similar to the examples seen earlier
      when discussing properties. As stated there, the properties notation is
      a short-hand notation for the invocation of bean getters and
      setters<footnote>
          <para>By explicitly stating the method name and parameters, the
          Uberspector is not used. This is useful if you object has both,
          <literal>get(String)</literal> and explicit property getter
          methods.</para>
        </footnote>.</para>

      <para>The main difference between properties and methods is that you can
      specify a parameter list to a method.</para>

      <example id="example-methods-that-can-be-used-with-shorthand-notation">
        <title>Methods that can be used with shorthand notation</title>

        <programlisting>$shop.getFruits()
$sun.getPlanets()
$album.get("logo")

$shop.setCustomer($customer)
$sun.setPlanetCount(9)
$album.put("logo", "newlogo")

## equal property getters and setters

$shop.fruits
$sun.Planets
$album.logo

#set ($shop.customer = $customer)
#set ($sun.planetCount = 9)
#set ($album.logo = "New Logo")</programlisting>
      </example>

      <warning>
        <para>The last <literal>#set</literal> example will not work in
        Velocity versions before 1.5 unless the <literal>$album</literal>
        object implements <literal>java.util.Map</literal>. This is a bug in
        older Velocity versions.</para>
      </warning>

      <para>Not every method invocation can be replaced by short hand
      notation. Even if a method is called
      <literal>set&lt;property&gt;()</literal> or
      <literal>get&lt;property&gt;()</literal>, it must still adhere to bean
      getter and setter method signatures.</para>

      <example id="example-methods-that-can-not-be-used-with-shorthand-notation">
        <title>Methods that can not be used with shorthand notation</title>

        <programlisting>## Can't pass a parameter with $sun.planet
$sun.getPlanet(3)

## Velocity only allows shorthand notation for getter and setter
$shop.orderFruits()

## Can't pass a parameter list
$book.setAuthorAndTitle("George Orwell", "Homage to Catalonia")</programlisting>
      </example>
    </section>

    <section id="section-reference-miscellany">
      <title>Reference miscellany</title>

      <section id="section-separating-identifiers-and-template-text">
        <title>Separating identifiers and template text</title>

        <para>When writing templates, you might encounter situations in which
        it is necessary to explicitly separate a reference from the
        surrounding template text. In the examples above, this was done
        implicitly through whitespace. Additionally there is a formal notation
        which wraps the identifiers with curly braces:</para>

        <example id="example-formal-notation-for-velocity-references">
          <title>Formal notation for Velocity references</title>

          <programlisting>${fruit}
${customer.address}
${purchase.getTotal()}</programlisting>
        </example>

        <para>Suppose you were building an extension to your fruit shop where
        juices are sold. <literal>$fruit</literal> contains the name of the
        juice which should be sold. Using the shorthand notation would be
        inadequate for this task. Consider the following example:</para>

        <example id="example-ambiguous-reference-name">
          <title>An ambiguous reference name</title>

          <programlisting>You have selected $fruitjuice.</programlisting>
        </example>

        <para>There is ambiguity here, and Velocity assumes that
        <literal>$fruitjuice</literal>, not <literal>$fruit</literal>, is the
        identifier that you want to use. Finding no value for
        <literal>$fruitjuice</literal>, it will return
        <literal>$fruitjuice</literal>. Using formal notation can resolve this
        problem.</para>

        <example id="example-using-formal-notation">
          <title>Using formal notation to resolve ambiguity</title>

          <programlisting>You have selected ${fruit}juice.</programlisting>
        </example>

        <para>Now Velocity knows that <literal>$fruit</literal>, not
        <literal>$fruitjuice</literal>, is the reference. Formal notation is
        often useful when references are directly adjacent to text in a
        template.</para>
      </section>

      <section id="section-quiet-reference-notation">
        <title>Quiet reference notation</title>

        <para>When Velocity encounters an undefined reference, its normal
        behavior is to output the image of the reference. For example, suppose
        the following reference appears as part of a VTL template.</para>

        <example id="example-non-quiet-input-form">
          <title>A web input form without quiet notation</title>

          <programlisting>&lt;input type="text" name="email" value="$email"/&gt;</programlisting>
        </example>

        <para>When the form initially loads, the variable reference
        <literal>$email</literal> has no value, but you probably prefer a
        blank text field to one with a value of <emphasis>$email</emphasis>.
        Using the quiet reference notation circumvents Velocity's normal
        behavior; instead of using <literal>$email</literal> in the VTL you
        would use <literal>$!email</literal>. So the above example would look
        like the following:</para>

        <example id="example-quiet-input-form">
          <title>A web input form with quiet notation</title>

          <programlisting>&lt;input type="text" name="email" value="$!email"/&gt;</programlisting>
        </example>

        <para>Now when the form is initially loaded and
        <literal>$email</literal> still has no value, an empty string will be
        output instead of <literal>$email</literal>.</para>

        <para>Formal and quiet reference notation can be used together:</para>

        <example id="example-quiet-formal-notation">
          <title>A web input form using quiet and formal notation
          together</title>

          <programlisting>&lt;input type="text" name="email" value="$!{email}"/&gt;</programlisting>
        </example>

        <caution>
          <para>It is very easy to confuse the quiet reference notation with
          the boolean <emphasis>not</emphasis>-Operator. Using the
          not-Operator, you use <literal>!${foo}</literal>, while the quiet
          reference notation is <literal>$!{foo}</literal>. And yes, you will
          end up sometimes with <literal>!$!{foo}</literal>...</para>
        </caution>
      </section>
    </section>
  </chapter>

  <chapter id="chapter-directives">
    <title>Directives</title>

    <para>References allow template designers to generate dynamic content for
    web sites, while <emphasis>directives</emphasis> permit web designers to
    truly take charge of the appearance and content of the web site. A
    directive is a script element that can be used to manipulate the rendering
    of the template.</para>

    <para>As described above, Velocity directives are part of either
    single or multi-line statements and are preceded by a hash sign
    (<literal>#</literal>). While the hash sign is technically not part of the
    directive, we will still speak about the <literal>#if</literal> or
    <literal>#set</literal> directive.</para>

    <para>Velocity knows about the following directives:<footnote>
        <para>If is possible to add custom directives through the Velocity
        configuration. These are merely the directives shipped with the
        default Velocity configuration. It is even possible to turn some of
        these off.</para>
      </footnote></para>

    <para><itemizedlist spacing="compact">
      <listitem>
        <para><literal>#set</literal> (single-line statement)</para>
      </listitem>

      <listitem>
        <para><literal>#literal</literal> (multi-line statement)</para>
      </listitem>

      <listitem>
        <para><literal>#if / #elseif / #else</literal> (multi-line
        statement)</para>
      </listitem>

      <listitem>
        <para><literal>#foreach</literal> (multi-line statement)</para>
      </listitem>

      <listitem>
        <para><literal>#include</literal> (single-line statement)</para>
      </listitem>

      <listitem>
        <para><literal>#parse</literal> (single-line statement)</para>
      </listitem>

      <listitem>
        <para><literal>#stop</literal> (single-line statement)</para>
      </listitem>

      <listitem>
        <para><literal>#macro</literal> (multi-line statement, see Chapter
        7)</para>
      </listitem>
    </itemizedlist></para>

    <section id="section-the-set-directive">
      <title>The #set directive</title>

      <para>The <literal>#set</literal> directive is used for setting the
      value of a reference.</para>

      <para>A value can be assigned to either a variable reference or a
      property reference.</para>

      <example id="example-value-assignment-using-the-set-directive">
        <title>Value assignment using the <emphasis>set</emphasis>
        directive</title>

        <programlisting>## Assigning a variable value
#set( $fruit = "apple" )

## Assigning a property value
#set( $customer.Favourite = $fruit )</programlisting>
      </example>

      <para>The left hand side (LHS) of the assignment must be a variable
      reference or a property reference. The right hand side (RHS) can be one
      of the following types:</para>

      <para><itemizedlist spacing="compact">
          <listitem>
            <para>Variable reference</para>
          </listitem>

          <listitem>
            <para>String literal</para>
          </listitem>

          <listitem>
            <para>Property reference</para>
          </listitem>

          <listitem>
            <para>Method reference</para>
          </listitem>

          <listitem>
            <para>Number literal</para>
          </listitem>

          <listitem>
            <para>List</para>
          </listitem>

          <listitem>
            <para>Map</para>
          </listitem>

          <listitem>
            <para>Expression</para>
          </listitem>
        </itemizedlist></para>

      <example id="example-valid-reference-assignments">
        <title>Valid reference assignments</title>

        <programlisting>## variable reference
#set( $fruit = $selectedFruit )

## string literal
#set( $fruit.flavor = "sweet" )

## property reference
#set( $fruit.amount = $cart.total )

## method reference
#set( $fruit.color = $colorlist.selectColor($select) )

## number literal
#set( $fruit.value = 123 )

## List
#set( $fruit.sorts = ["Apple", "Pear", "Orange"] )

## Map
#set( $fruit.shapes = {"Apple" : "round", "Pear" : "conical"}) </programlisting>
      </example>

      <note>
        <para>For the List example the elements defined with the
        <literal>[..]</literal> operator are accessible using the methods
        defined in the <literal>java.util.List</literal> class. So, for
        example, you could access the first element above using
        <literal>$fruit.sorts.get(0)</literal>.</para>

        <para>Similarly, for the Map example, the elements defined within the
        <literal>{..}</literal> operator are accessible using the methods
        defined in the <literal>java.util.Map</literal> class. You can access
        the first element above using
        <literal>$fruit.shapes.get("Apple")</literal> to return the String
        <literal>round</literal>, or even
        <literal>$fruit.shapes.Apple</literal> to return the same
        value.</para>
      </note>

      <para>The RHS can also be an arithmetic expression as described in the
      Math chapter below.</para>

      <example id="example-expression-examples">
        <title>Expression examples</title>

        <programlisting>#set( $value = $foo + 1 )
#set( $value = $bar - 1 )
#set( $value = $foo * $bar )
#set( $value = $foo / $bar )</programlisting>
      </example>

      <section id="section-assigning-null-values-to-references">
        <title>Assigning null values to references</title>

        <para>In its default configuration, Velocity treats
        <literal>null</literal> values on the RHS special. If your developers
        don't change the default configuration, you must understand that it is
        not possible to assign a null value through a <literal>set</literal>
        directive to a reference. Starting with Velocity 1.5, a runtime
        property (<literal>directive.set.null.allowed</literal>) exists that
        removes this restriction. If you do not want <literal>null</literal>
        values to be treated special, tell your application developers that
        they should look up this property in the Velocity Developers Guide and
        set it to true.</para>

        <note>
          <para>Removing this restriction is one of the new features of
          Velocity 1.5. If you are maintaining existing template code from
          older Velocity versions, you probably want to keep the old
          behaviour.</para>

          <para>For new developments based on Velocity 1.5 and beyond, we
          strongly recommend that you don't treat null values on the RHS
          special (set <literal>directive.set.null.allowed</literal> to be
          true). This will be the default behaviour in future Velocity
          versions.</para>
        </note>

        <para>The remainder of this chapter assumes that you kept the default
        configuration of Velocity.</para>

        <para>If the RHS is a property or method reference that evaluates to
        <literal>null</literal>, it will <emphasis>not</emphasis> be assigned
        to the LHS and the LHS <emphasis>will not be altered</emphasis>. This
        is very different from the behaviour in e.g. the Java programming
        language and needs some discussion.</para>

        <para>In the following piece of code, two queries are executed using
        the same set of template references:</para>

        <programlisting>#set( $result = $query.criteria("fruit") )
The result of the first query is $result

#set( $result = $query.criteria("customer") )
The result of the second query is $result</programlisting>

        <para>If <literal>$query.criteria("name")</literal> returns the string
        "apple", and <literal>$query.criteria("customer")</literal> returns
        null, the above VTL will render as the follows:</para>

        <programlisting>The result of the first query is apple

The result of the second query is apple</programlisting>

        <para>In the second <literal>set</literal> directive, the RHS is null,
        because <literal>$query.criteria("customer")</literal> returned null.
        So the RHS will not be modified (and the old value retained).</para>

        <para>Unfortunately, this can lead to hard-to-detect errors, for
        example with <literal>#foreach</literal> loops that attempt to change
        a reference using a <literal>#set</literal> directive, then
        immediately test that reference with an <literal>#if</literal>
        directive:</para>

        <programlisting>#set( $criteria = ["fruit", "customer"] )

#foreach( $criterion in $criteria )

  #set( $result = $query.criteria($criterion) )

  #if( $result )
    Query was successful
  #end

#end</programlisting>

        <para>In the above example, it would not be wise to rely on the
        evaluation of <literal>$result</literal> to determine if a query was
        successful. After <literal>$result</literal> has been set (added to
        the context), it cannot be set back to null (removed from the
        context).</para>

        <para>One solution to this would be to reset the value of
        <literal>$result</literal> in every loop iteration:</para>

        <programlisting>#set( $criteria = ["name", "address"] )

#foreach( $criterion in $criteria )

  #set( $result = "" )
  #set( $result = $query.criteria($criterion) )

  #if( $result != "" )
    Query was successful
  #end

#end</programlisting>

        <para>However, the easiest way is to use the quiet reference
        notation:</para>

        <programlisting>#set( $criteria = ["name", "address"] )

#foreach( $criterion in $criteria )

  #set( $result = $!query.criteria($criterion) )

  #if( $result != "" )
    Query was successful
  #end

#end</programlisting>

        <para>If the query fails, <literal>$result</literal> gets the empty
        string assigned.</para>
      </section>

      <?hard-pagebreak ?>

      <section id="section-string-literals">
        <title>String Literals</title>

        <para>When using the <literal>#set</literal> directive, string
        literals that are enclosed in double quote characters will be parsed
        and rendered, as shown:</para>

        <example id="example-double-quoted-string-literal">
          <title>Evaluating a double-quoted string literal</title>

          <programlisting>#set( $directoryRoot = "www" )
#set( $templateName = "index.vm" )
#set( $template = "$directoryRoot/$templateName" )
$template</programlisting>
        </example>

        <para>The output will be:</para>

        <programlisting>www/index.vm</programlisting>

        <para>However, when the string literal is enclosed in single quote
        characters, it will not be parsed:</para>

        <example id="example-evaluating-string-literals">
          <title>Single and double-quoted string literals</title>

          <programlisting>#set( $fruit = "apple" )
$fruit

#set( $veggie = '$fruit' )
$veggie</programlisting>
        </example>

        <para>The output will be:</para>

        <programlisting>apple

$fruit</programlisting>

        <para>By default, rendering unparsed text using single quotes is
        activated in Velocity. This default can be changed by changing the
        <literal>runtime.interpolate.string.literals</literal> property to be
        false. (See the Velocity Developers Guide for more
        information).</para>
      </section>
    </section>

      <?hard-pagebreak ?>
    <section id="section-the-literal-directive">
      <title>The #literal directive</title>

      <para>The <literal>#literal</literal> directive allows you to easily use
      large chunks of uninterpreted content in VTL code. This can be
      especially useful in place of escaping multiple directives. #literal is
      a multi-line statement and needs a #end directive to close the statement
      body.</para>

      <example id="example-using-the-literal-directive">
        <title>Using the <literal>#literal</literal> directive</title>

        <programlisting>#literal()
#foreach ($fruit in $basket)
  nothing will happen to $fruit
#end
#end</programlisting>
      </example>

      <para>The output will be:</para>

      <programlisting>#foreach ($fruit in $basket)
  nothing will happen to $fruit
#end</programlisting>

      <para>Even if the <literal>$fruit</literal> or
      <literal>$basket</literal> references have a value assigned, the text
      will still be output uninterpreted.</para>

      <caution>
        <para>While <literal>#literal</literal> suppresses the evaluation of
        Velocity directives and references at run-time, the body is still
        parsed. <literal>#literal</literal> is not a comment block, if you
        have a syntax error (e.g. a missing <literal>#end</literal>) inside
        the block, Velocity will still report a parse error.</para>
      </caution>
    </section>

      <?hard-pagebreak ?>
    <section id="section-conditionals-if-elseif-else">
      <title>Conditionals - #if/#elseif/#else</title>

      <para>The <literal>#if</literal> directive in Velocity allows for text
      to be included when the web page is generated, on the conditional that
      the <literal>#if</literal> statement is true. Consider the following
      piece of code:</para>

      <example id="example-using-the-if-directive">
        <title>Using the <literal>#if</literal> directive</title>

        <programlisting>#if( $display )
  &lt;strong&gt;Velocity!&lt;/strong&gt;
#end</programlisting>
      </example>

      <para>The variable <literal>$display</literal> is evaluated to determine
      whether it is true, which will happen under one of two circumstances:
      <itemizedlist>
          <listitem>
            <para><literal>$display</literal> is a
            <literal>java.lang.Boolean</literal> object (True/False) which has
            a true value.</para>
          </listitem>

          <listitem>
            <para>The value is not null.</para>
          </listitem>
        </itemizedlist></para>

      <para>The Velocity context only contains Java objects, so any method
      that returns a boolean primitive will automatically wrapped into a
      <literal>java.lang.Boolean</literal> object.</para>

      <para>The content between the <literal>#if</literal> and the
      <literal>#end</literal> statements becomes the output if the evaluation
      is true. In this case, if <literal>$display</literal> is true, the
      output will be: <computeroutput>Velocity!</computeroutput>. Conversely,
      if <literal>$display</literal> has a null value, or if it is a boolean
      false, the statement evaluates as false, and there is no output.</para>

      <para>An <literal>#elseif</literal> or <literal>#else</literal> element
      can be used with an <literal>#if</literal> element. Note that Velocity
      will stop at the first expression that is found to be true:</para>

      <example id="example-using-if-elseif-else-to-select-multiple-template-pieces">
        <title>Using #if/#elseif/#else to select multiple template
        pieces</title>

        <programlisting>#set ($direction = 15)
#set ($wind = 6)

#if( $direction &lt; 10 )
  &lt;strong&gt;Go North&lt;/strong&gt;
#elseif( $direction == 10 )
  &lt;strong&gt;Go East&lt;/strong&gt;
#elseif( $wind == 6 )
  &lt;strong&gt;Go South&lt;/strong&gt;
#else
  &lt;strong&gt;Go West&lt;/strong&gt;
#end</programlisting>
      </example>

      <para>In this example, <literal>$direction</literal> is greater than 10,
      so the first two comparisons fail. Next <literal>$wind</literal> is
      compared to 6, which is true, so the output is <computeroutput>Go
      South</computeroutput>.</para>

      <para>When you wish to include text immediately following a
      <literal>#else</literal> directive you need to use curly brackets
      surrounding the directive to differentiate it from the following
      text:</para>

      <example id="example-if-directive-in-formal-notation">
        <title>The <literal>#if</literal> directive in formal notation</title>

        <programlisting>#if( $foo == $bar)it is true!#{else}it is not!#end&lt;/li&gt;</programlisting>
      </example>
    </section>

    <section id="section-loops-foreach">
      <title>Loops - #foreach</title>

      <para><literal>#foreach</literal> iterates over the elements given in a
      List or Array element.</para>

      <example id="example-foreach-loop-example">
        <title>A <literal>#foreach</literal> loop example</title>

        <programlisting>&lt;ul&gt;
  #foreach( $product in $allProducts )
    &lt;li&gt;$product&lt;/li&gt;
  #end
&lt;/ul&gt;</programlisting>
      </example>

      <para>Unlike other languages, the Velocity templating language allows
      only loops where the number of iterations is predetermined. There is no
      <literal>do..while</literal> or <literal>repeat..until</literal> loop in
      Velocity. This has been a conscious decision to make sure that the
      rendering process of Velocity does always terminate<footnote>
          <para>It is stil possible to write a template that contains endless
          loops. It is just harder.</para>
        </footnote>.</para>

      <para>A VTL foreach loop takes two arguments, the first one is the
      <firstterm>loop variable</firstterm> and the second is an object that
      can be iterated over. Velocity supports a number of object types in its
      default configuration<footnote>
          <para>The list of objects can be changed and extended, please see
          the Velocity Developers Guide on how to do this.</para>
        </footnote>:</para><para><itemizedlist spacing="compact">
          <listitem>
            <para>Any array type</para>
          </listitem>

          <listitem>
            <para><literal>java.lang.Collection</literal> - The loop iterates
            over the Iterator returned by obj.iterator()</para>
          </listitem>

          <listitem>
            <para><literal>java.lang.Map</literal> - The loop will iterate
            over the values of the Map using the iterator returned by
            values().iterator()</para>
          </listitem>

          <listitem>
            <para><literal>java.lang.Iterator</literal> - Velocity uses this
            iterator directly</para>
          </listitem>

          <listitem>
            <para><literal>java.lang.Enumeration</literal> - Velocity wrapping
            the Enumeration into an Iterator</para>
          </listitem>
        </itemizedlist></para>

      <warning>
        <para>Using an Iterator or Enumeration object directly in a template
        has the side effect that the loop cannot be evaluated multiple times
        because the loop consumes the object that gets iterated. Be especially
        careful if you use such an object inside a Velocimacro or an included
        template.</para>
      </warning>

      <para>Velocity provides you with a loop counter reference which contains
      the number of the current iteration of the loop:</para>

      <example id="example-using-the-loop-counter">
        <title>Using the loop counter</title>

        <programlisting>&lt;table&gt;
  #foreach( $customer in $customerList )
    &lt;tr&gt;&lt;td&gt;$velocityCount&lt;/td&gt;&lt;td&gt;$customer.Name&lt;/td&gt;&lt;/tr&gt;
  #end
&lt;/table&gt;</programlisting>
      </example>

      <para>The default name for the loop counter and its starting value is
      specified through runtime settings. By default it starts at 1 and is
      called <literal>$velocityCount</literal>. If you need these values
      changed, consult your Java developers and the Velocity Developers
      Guide.</para>

      <programlisting># Default name of the loop counter
# variable reference.
directive.foreach.counter.name = velocityCount

# Default starting value of the loop
# counter variable reference.
directive.foreach.counter.initial.value = 1</programlisting>

      <para>The Velocity loop counter variable does support nested loops, so
      the following example would work as expected:</para>

      <example id="example-nested-loops-and-the-loop-counter">
        <title>Nested Loops and the loop counter</title>

        <programlisting>#foreach ($category in $allCategories)
  Category # $velocityCount is $category

  #foreach ($item in $allItems)
    Item # $velocitycount is $item
  #end

#end</programlisting>
      </example>

      <para>The loop counter is local to its surrounding loop and any inner
      loops hides but not resets it. Please note that it is not possible to
      access the count variable of the outer loop directly inside the inner
      loop<footnote>
          <para>You can assign its value to another variable before entering
          the inner loop using <literal>#set</literal> and access it through
          this variable inside the inner loop.</para>
        </footnote>.</para>

      <para>To avoid deadlocks and denial of service attacks, it is possible
      to set a maximum allowed number of times that a loop may be executed. By
      default there is no limit, but it can be set to an arbitrary number in
      the Velocity configuration.</para>

      <programlisting># The maximum allowed number of loops.
directive.foreach.maxloops = -1</programlisting>
    </section>

      <?hard-pagebreak ?>

    <section id="section-stop-template-rendering-stop">
      <title>Stop template rendering - #stop</title>

      <para>The <literal>#stop</literal> directive stops the rendering of a
      template. The remaining part of the template after this directive is
      discarded. The most common usage of this directive is debugging
      templates<footnote>
            <para>It is possible to do strange things by using the
            <literal>#stop</literal> directive inside <literal>#if ... #else
            ... #end</literal> blocks. As <literal>#stop</literal> only ends
            the rendering if it is actually encountered, it is possible to
            skip over the directive.</para>
          </footnote>.</para>

      <example id="example-using-stop-to-end-template-rendering">
        <title>Using <literal>#stop</literal> to end template
        rendering</title>

        <programlisting>This part gets rendered in the output.
#stop
This part does not get rendered.</programlisting>
      </example>

      <para>The <literal>#stop</literal> directive can also be written as
      <literal>#stop()</literal>.</para>

      <caution>
        <para>While <literal>#stop</literal> ends the rendering process, it
        <emphasis>does not</emphasis> affect the template parsing. If you have
        a syntax error in the VTL code after the <literal>#stop</literal>
        directive, this error will still be reported.</para>
      </caution>
    </section>

    <section id="section-loading-resources">
      <title>Loading resources</title>

      <para>In Velocity, just as in other rendering techniques like JSP, it is
      important to build output from multiple input files. For this, you need
      to be able to pull external resources into the rendering process.</para>

      <note>
        <para>For convenience, we will talk about files in the reminder of
        this chapter. A template needs not to be a file and strictly spoken, a
        template can be loaded from arbitrary sources including databases.
        Using files for templates and referring to their names as file pathes
        with directories is just the most common way.</para>
      </note>

      <para>Velocity supports the loading of external templates by the
      <literal>#include</literal> and <literal>#parse</literal> directive,
      which both load external resources into the rendering process of a
      template.</para>

      <para>Velocity does not allow you to include arbitrary templates into
      your templates for security reasons. All included elements will be
      loaded with a <firstterm>resource loader</firstterm> set up in the
      Velocity configuration. Please consult the Developers Guide for
      information on how to do this.</para>

      <?hard-pagebreak ?>

      <section id="section-file-inclusion-include">
        <title>File inclusion - #include</title>

        <para>The <literal>#include</literal> directive allows the template
        designer to import a local file. Its contents replace the
        <literal>#include</literal> directive in the template. These contents
        are inserted as-is, they are not rendered through the template
        engine.</para>

        <para>Multiple files can be loaded through a single #include
        directive, their names must be separated by commas.</para>

        <example id="example-including-files-into-a-velocity-template">
          <title>Including files into a Velocity Template</title>

          <programlisting>## Load the file one.txt into this template
#include( "one.txt" )

## Load multiple files into this template
#include( "one.txt","two.txt","three.txt" )</programlisting>
        </example>

        <para>The file being included need not be referenced by name; in fact,
        it is often preferable to use a variable instead of a filename. This
        could be useful for targeting output according to criteria determined
        when the page request is submitted.</para>

        <example id="example-including-a-file-by-a-variable-reference">
          <title>Including a file named by a variable reference</title>

          <programlisting>#set ($seasonalgreetings = "christmas.txt")
#include( "greetings.txt", $seasonalgreetings )</programlisting>
        </example>
      </section>

      <section id="section-template-inclusion-parse">
        <title>Template inclusion - #parse</title>

        <para>The <literal>#parse</literal> directive works similar to
        <literal>#include</literal>, but the contents of the file will be part
        of the template rendering process and all VTL elements in the file
        will be evaluted. The output will replace the
        <literal>#parse</literal> directive in the importing template.</para>

        <example id="example-including-an-external-template">
          <title>Including an external template</title>

          <programlisting>#parse( "one.vm" )</programlisting>
        </example>

        <para>Like the <literal>#include</literal> directive,
        <literal>#parse</literal> can take a variable rather than a template.
        Unlike the <literal>#include</literal> directive,
        <literal>#parse</literal> will only take a single argument, you cannot
        load multiple templates with a single <literal>#parse</literal>
        directive.</para>

        <para>Recursion is permitted; VTL templates can have
        <literal>#parse</literal> statements referring to templates that in
        turn have <literal>#parse</literal> statements.</para>

        <para>To avoid infinitive recursion, the number of levels is limited
        through a configuration property. It is not possible to configure an
        infinite recursion depth. The default maximum number of recursions is
        20<footnote>
            <para>As we said, we wanted to make it hard to write templates
            that contain endless loops. Allowing unlimited recursion would
            have been too easy.</para>
          </footnote>.</para>

        <programlisting># Maximum number of #parse levels
directive.parse.max.depth = 10</programlisting>

        <example id="example-parsing-a-recursive-template">
          <title>Parsing a recursive template</title>

          <programlisting>## ########################################
## Template "countdown.vm"
## ########################################
Count down.

#set( $count = 8 )
#parse( "counter.vm" )
All done with countdown.vm!
## ########################################


## ########################################
## Template "counter.vm
## ########################################
$count
#set( $count = $count - 1 )
#if( $count &gt; 0 )
  #parse("counter.vm" )
#else
  All done with counter.vm!
#end
## ########################################


The resulting output:

Count down.
8
7
6
5
4
3
2
1
0

All done with counter.vm!
All done with countdown.vm!</programlisting>
        </example>

      </section>
    </section>

  </chapter>

  <chapter id="chapter-operators">
    <title>Operators</title>

    <para>Velocity knows a number of relational and logical operators. They
    can be used everywhere an expression is evaluated, most prominently in
    <literal>#if</literal> and <literal>#set</literal> directives.</para>

    <para>Each operator is available in two notations, a short version which
    is roughly equal to the Java notation and a text representation which can
    be used to avoid problems e.g. with XML templates and the
    <literal>&lt;</literal>, <literal>&gt;</literal> and
    <literal>&amp;&amp;</literal> operators.<example
        id="example-using-operators">
        <title>Using operators</title>

        <para><programlisting>#set ($a = true)
#set ($b = false)

#if ($a || $b)
  short version 'or' was true
#end

#if ($a and $b)
  text version 'and' was true
#end</programlisting></para>
      </example></para>

    <table id="table-velocity-relational-and-logical-operators">
      <title>Velocity Relational and logical operators</title>

      <tgroup cols="3">
        <thead>
          <row>
            <entry align="center">Type of operator</entry>

            <entry align="center">short version</entry>

            <entry>text version</entry>
          </row>
        </thead>

        <tbody>
          <row>
            <entry>equal<footnote>
                <para>Note that the semantics of the equal operator are
                slightly different than Java where <literal>==</literal> can
                only be used to test object equality. In Velocity the
                equivalent operator can be used to directly compare numbers,
                strings, or objects. When the objects are of different
                classes, the string representations are obtained by calling
                <literal>toString()</literal> for each object and then
                compared.</para>
              </footnote></entry>

            <entry>==</entry>

            <entry>eq</entry>
          </row>

          <row>
            <entry>not equal</entry>

            <entry>!=</entry>

            <entry>ne</entry>
          </row>

          <row>
            <entry>greater than</entry>

            <entry>&gt;</entry>

            <entry>gt</entry>
          </row>

          <row>
            <entry>greater or equal than</entry>

            <entry>&gt;=</entry>

            <entry>ge</entry>
          </row>

          <row>
            <entry>less than</entry>

            <entry>&lt;</entry>

            <entry>lt</entry>
          </row>

          <row>
            <entry>less or equal than</entry>

            <entry>&lt;=</entry>

            <entry>le</entry>
          </row>

          <row>
            <entry>logical and</entry>

            <entry>&amp;&amp;</entry>

            <entry>and</entry>
          </row>

          <row>
            <entry>logical or</entry>

            <entry>||</entry>

            <entry>or</entry>
          </row>

          <row>
            <entry>logical not</entry>

            <entry>!</entry>

            <entry>not</entry>
          </row>
        </tbody>
      </tgroup>
    </table>

    <para><caution>
        <para>Unlike other languages, Velocity does not consider the number 0
        (zero) or the empty String ('') to be equivalent to false. Only the
        boolean value false (primitive oder <literal>Boolean.FALSE</literal>)
        and null are evaluated to false. Everything else evaluates to
        true.</para><para>This was a conscious decision by the Velocity designers and
            is not likely to change.</para>
      </caution>Here is a simple example to illustrate how the equivalent
    operator is used.</para>

    <example id="example-using-the-equivalent-operator">
      <title>Using the equivalent operator</title>

      <programlisting>#set ($foo = "deoxyribonucleic acid")
#set ($bar = "ribonucleic acid")

#if ($foo == $bar)
  In this case it is clear they aren't equivalent. So...
#else
  They are not equivalent and this will be the output.
#end</programlisting>
    </example>

    <para>The text versions of all logical operators can be used to avoid
    problems with &amp;, &lt;, and &gt; in XML templates.</para>

    <section id="section-the-and-operator">
      <title>The AND Operator</title>

      <example id="example-using-logical-and">
        <title>Using logical AND</title>

        <programlisting>#if( $this &amp;&amp; $that )
  &lt;strong&gt;This AND that&lt;/strong&gt;
#end</programlisting>
      </example>

      <para>The <literal>#if</literal> directive will only evaluate to true if
      both <literal>$this</literal> and <literal>$that</literal> are true. If
      <literal>$this</literal> is false, the expression will evaluate to
      false; <literal>$that</literal> will not be evaluated. If
      <literal>$this</literal> is true, then Velocity will then check the
      value of <literal>$that</literal>; if <literal>$that</literal> is true,
      then the entire expression is true and This AND that becomes the output.
      If <literal>$that</literal> is false, then there will be no output as
      the entire expression is false.</para>
    </section>

    <section id="section-the-or-operator">
      <title>The OR Operator</title>

      <para>Logical OR operators work the same way as AND operators, except
      only one of the references need evaluate to true in order for the entire
      expression to be considered true. Consider the following example:</para>

      <example id="example-using-logical-or">
        <title>Using logical OR</title>

        <programlisting>#if( $this || $that )
  &lt;strong&gt;This OR That&lt;/strong&gt;
#end</programlisting>
      </example>

      <para>If <literal>$this</literal> is true, the Velocity templating
      engine has no need to look at <literal>$that</literal>; whether
      <literal>$that</literal> is true or false, the expression will be true,
      and This OR That will be output. If <literal>$this</literal> is false,
      however, <literal>$that</literal> must be checked. In this case, if
      <literal>$that</literal> is also false, the expression evaluates to
      false and there is no output. On the other hand, if
      <literal>$that</literal> is true, then the entire expression is true,
      and the output is This OR That</para>
    </section>

    <section id="section-the-not-operator">
      <title>The NOT Operator</title>

      <para>With logical NOT operators, there is only one argument:</para>

      <example id="example-using-logical-not">
        <title>Using logical NOT</title>

        <programlisting>#if( !$that )
  &lt;strong&gt;NOT that&lt;/strong&gt;
#end</programlisting>
      </example>

      <para>Here, the if <literal>$that</literal> is true, then
      <literal>!$that</literal> evaluates to false, and there is no output. If
      <literal>$that</literal> is false, then <literal>!$that</literal>
      evaluates to true and <computeroutput>NOT that</computeroutput> will be
      output. Be careful not to confuse this with the <emphasis>quiet
      reference </emphasis><literal>$!foo</literal>.</para>
    </section>
  </chapter>

  <chapter id="chapter-velocity-macros">
    <title>Velocity Macros</title>

    <para>The <literal>#macro</literal> directive allows you to name a section
    of a VTL template and re-insert it multiple times into the template. A
    Velocity macro (or short <firstterm>Velocimacro</firstterm>) can be used
    in many different scenarios.</para>

    <para>In the following example, a Velocimacro is created to save
    keystrokes and minimize typographic errors:</para>

    <programlisting>#macro( d ) &lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt; #end</programlisting>

    <para>This example defines a Velocimacro called <literal>d</literal>. It
    now can be uses as any other VTL directive:</para>

    <programlisting>#d()</programlisting>

    <para>When this template is rendered, Velocity replaces
    <literal>#d()</literal> with the HTML table row containing a single, empty
    cell defined above. Using a Velocimacro in a template is called
    <firstterm>macro invocation</firstterm>.</para>

    <para>A Velocimacro definition starts with the <literal>#macro</literal>
    directive and are ended with <literal>#end</literal>. The enclosed block
    is the <firstterm>macro body</firstterm>. Whenever a Velocimacro is
    invoked, its body is inserted in the template. It is rendered at every
    invokation through the templating engine, with the invocation arguments
    replacing the arguments in the Velocimacro definition.</para>

    <para>A Velocimacro can take any number of arguments including zero, but
    when it is invoked, it must be called with exactly the same number of
    arguments that it was defined with.</para>

    <para>Here is a Velocimacro that takes two arguments, a color and a list
    of objects:</para>

    <example id="example-macro-with-two-arguments">
      <title>A macro that takes two arguments</title>

      <programlisting>#macro( tablerows $color $values )
  #foreach( $value in $values )
    &lt;tr&gt;&lt;td bgcolor=$color&gt;$value&lt;/td&gt;&lt;/tr&gt;
  #end
#end

#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )

&lt;table&gt;
  #tablerows( $color $greatlakes )
&lt;/table&gt;</programlisting>
    </example>

    <para>The <literal>tablerows</literal> Velocimacro takes exactly two
    arguments. The first argument takes the place of
    <literal>$color</literal>, and the second argument takes the place of
    <literal>$values</literal>. Anything that can be put into a VTL template
    can go into the body of a Velocimacro.</para>

    <para>Notice that <literal>$greatlakes</literal> takes the place of
    <literal>$values</literal>. When this template is rendered, the following
    output is generated:</para>

    <programlisting>&lt;table&gt;
&lt;tr&gt;&lt;td bgcolor="blue"&gt;Superior&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td bgcolor="blue"&gt;Michigan&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td bgcolor="blue"&gt;Huron&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td bgcolor="blue"&gt;Erie&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td bgcolor="blue"&gt;Ontario&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;</programlisting>

    <para>In the example above, the <literal>#tablerows</literal> Velocimacro
    was defined as an <firstterm>inline macro</firstterm>. Another way to
    declare a macro is in a <firstterm>Velocimacro library</firstterm>, it is
    then called a <firstterm>global macro</firstterm>. An inline Velocimacro
    is only visible in the template where it is defined, a global Velocimacro
    is accessible from all templates. Global definitions must be done in a a
    Velocimacro template library, which is a template file that contains the
    macros and they must be referenced explicitly through the Velocity
    configuration. Please see the Velocity Reference Guide for more
    information on how to define and load a macro library.</para>

    <para>If the <literal>#tablerows($color $values)</literal> Velocimacro is
    defined a Velocimacro template library, it could be in any template. In
    the fruit store it could be used to list fruits available:</para>

    <programlisting>#set( $fruits = ["apple", "pear", "orange", "strawberry"] )
#set($cellbgcol = "white" )

&lt;table&gt;
  #tablerows( $cellbgcol $fruits )
&lt;/table&gt;</programlisting>

    <para>When rendering this template, Velocity would find the
    <literal>#tablerows</literal> Velocimacro in a template library (defined
    in the Velocity configuration) and generate the following output:</para>

    <programlisting>&lt;table&gt;
  &lt;tr&gt;&lt;td bgcolor="white"&gt;apple&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td bgcolor="white"&gt;pear&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td bgcolor="white"&gt;orange&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td bgcolor="white"&gt;strawberry&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;</programlisting>

      <?hard-pagebreak ?>

    <section id="section-velocimacro-arguments">
      <title>Velocimacro Arguments</title>

      <para>Velocimacros can take as arguments any of the following VTL
      elements:</para>

      <para><itemizedlist spacing="compact">
        <listitem>
          <para>A reference, starting with <literal>$</literal></para>
        </listitem>

        <listitem>
          <para>A String literal, enclosed in single or double quotes</para>
        </listitem>

        <listitem>
          <para>A Number literal (1, 2, 3 etc.)</para>
        </listitem>

        <listitem>
          <para>An IntegerRange ([ 1..2] or [$start .. $end])</para>
        </listitem>

        <listitem>
          <para>An ObjectArray ([ "a", "b", "c"])</para>
        </listitem>

        <listitem>
          <para><literal>true</literal> and <literal>false</literal> for
          boolean values representing true and false</para>
        </listitem>
      </itemizedlist></para>

      <para>When passing references as arguments to Velocimacros, please note
      that references are passed <emphasis>by name</emphasis>. This means that
      their value is evaluated each time it is used inside the Velocimacro.
      This feature allows you to pass references with method calls and have
      the method called at each use:</para>

      <example id="example-passing-parameters-by-name">
        <title>Passing parameters by name</title>

        <programlisting>#macro( callme $a )
  $a $a $a
#end

#callme( $foo.bar() )</programlisting>
      </example>

      <para>results in the method <literal>bar()</literal> of the reference
      <literal>$foo</literal> being called 3 times.</para>

      <caution>
        <para>If you are used to the behaviour of method or procedure calls in
        programming languages like Java or C, please be sure to fully
        understand the implications of <emphasis>passing by name</emphasis>.
        Unlike these programming languages, the reference is not evaluated at
        macro invocation time but at every occurence inside the Velocimacro.
        Don't treat Velocimacros as procedures or methods!</para>
      </caution>

      <para>The easiest way to avoid any gotchas is not passing any stateful
      object into a Velocimacro. This can be done by assigning the result of a
      method invocation to a new reference:</para>

      <example id="example-resolving-a-stateful-object">
        <title>Resolving a stateful object before macro invocation</title>

        <programlisting>#set( $myval = $foo.bar() )
#callme( $myval )</programlisting>
      </example>
    </section>

      <?hard-pagebreak ?>

    <section id="section-velocimacro-properties">
      <title>Velocimacro Properties</title>

      <para>There are a number of properties in the Velocity configuration
      that influence the behaviour of the Velocimacros. A complete list of all
      configuration options is in the Velocity Reference Guide.</para>

      <variablelist>
        <varlistentry>
          <term><literal>velocimacro.library</literal></term>

          <listitem>
            <para>A comma-separated list of all Velocimacro template
            libraries. By default, Velocity looks for a single library:
            <filename><literal>VM_global_library.vm</literal></filename>. The
            configured template path is used to find the Velocimacro
            libraries.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term><literal>velocimacro.permissions.allow.inline</literal></term>

          <listitem>
            <para>This property, which has possible values of true or false,
            determines whether Velocimacros can be defined in regular
            templates. The default, true, allows template designers to define
            Velocimacros in the templates themselves.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term><literal>velocimacro.permissions.allow.inline.to.replace.global</literal></term>

          <listitem>
            <para>With possible values of true or false, this property allows
            the user to specify if a Velocimacro defined inline in a template
            can replace a globally defined template, one that was loaded on
            startup via the <literal>velocimacro.library</literal> property.
            The default, false, prevents Velocimacros defined inline in a
            template from replacing those defined in the template libraries
            loaded at startup.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term><literal>velocimacro.permissions.allow.inline.local.scope</literal></term>

          <listitem>
            <para>This property, with possible values of true or false,
            defaulting to false, controls if Velocimacros defined inline are
            'visible' only to the defining template. In other words, with this
            property set to true, a template can define inline VMs that are
            usable only by the defining template. You can use this for fancy
            VM tricks - if a global VM calls another global VM, with inline
            scope, a template can define a private implementation of the
            second VM that will be called by the first VM when invoked by that
            template. All other templates are unaffected.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term><literal>velocimacro.context.localscope</literal></term>

          <listitem>
            <para>This property has the possible values true or false, and the
            default is false. When true, any modifications to the context via
            #set() within a Velocimacro are considered 'local' to the
            Velocimacro, and will not permanently affect the context.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term><literal>velocimacro.library.autoreload</literal></term>

          <listitem>
            <para>This property controls Velocimacro library autoloading. The
            default value is false. When set to true the source Velocimacro
            library for an invoked Velocimacro will be checked for changes,
            and reloaded if necessary. This allows you to change and test
            Velocimacro libraries without having to restart your application
            or servlet container, just like you can with regular templates.
            This mode only works when caching is turned off in the resource
            loaders (see the Velocity Reference Guide on how to do this). This
            feature is intended for development, not for production.</para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section>

      <?hard-pagebreak ?>

    <section id="section-velocimacro-trivira">
      <title>Velocimacro Trivia</title>
      <qandaset>
        <qandadiv>
          <qandaentry>
            <question>
              <para>Must a Velocimacro be defined before it can be
              used?</para>
            </question>

            <answer>
              <para><emphasis>Yes</emphasis>. Velocimacros must be defined
              before they are first used in a template. This means that your
              inline <literal>#macro</literal> declarations must be found by
              the engine before usage.</para>

              <para>This is important to remember if you try to
              <literal>#parse</literal> a template containing inline
              <literal>#macro</literal> directives. Because the
              <literal>#parse</literal> invocation happens <emphasis>at
              runtime</emphasis>, and the parser looks at the Velocimacro
              definitions earlier, at <emphasis>parsetime</emphasis>. So
              loading a set of Velocimacro definitions using
              <literal>#parse</literal> does not work. If you need to use a
              set of Velocimacros on more than one template, declare it as a
              Velocimacro Library in the Velocity configuration.</para>
            </answer>
          </qandaentry>

          <qandaentry>
            <question>
              <para>Can I use a directive or another Velocimacro as an
              argument to a Velocimacro?</para>

              <programlisting>Example: <literal>#center( #bold("hello") )</literal></programlisting>
            </question>

            <answer>
              <para><emphasis>No</emphasis>. A directive isn't a valid
              argument to a directive, and for most practical purposes, a
              Velocimacro is a directive.</para>

              <para>However, there are things you can do. One easy solution is
              to take advantage of the fact that a doublequoted string (")
              renders its contents. So you could do something like</para>

              <programlisting>#set($stuff = "#bold('hello')" )
#center( $stuff )</programlisting>

              <para>You can save a step...</para>

              <programlisting>#center( "#bold( 'hello' )" )</programlisting>

              <para>Please note that in the latter example the arg is
              evaluated <emphasis>inside</emphasis> the Velocimacro, not at
              the calling level. In other words, the argument to the
              Velocimacro is passed in in its entirety and evaluated within
              the Velocimacro it was passed into. This allows you to do things
              like:</para>

              <programlisting>#macro( inner $foo )
  inner: $foo
#end

#macro( outer $foo )
  #set($bar = "value")
  outer: $foo
#end

#set($bar = 'calltimelala')
#outer( "#inner($bar)" )</programlisting>

              <para>Where the output is</para>

              <programlisting>Outer: inner: value</programlisting>

              <para>because the evaluation of the
              <literal>"#inner($bar)"</literal> happens inside
              <literal>#outer</literal>, so the <literal>$bar</literal> value
              set inside <literal>#outer</literal> is the one that is
              used.</para>

              <para>This is an intentional and jealously guarded feature -
              arguments are passed <emphasis>by name</emphasis> into
              Velocimacros, so you can hand Velocimacros things like stateful
              references such as</para>

              <programlisting>#macro( foo $color )
  &lt;tr bgcolor="$color"&gt;&lt;td&gt;Hi&lt;/td&gt;&lt;/tr&gt;
  &lt;tr bgcolor="$color"&gt;&lt;td&gt;There&lt;/td&gt;&lt;/tr&gt;
#end

#foo($bar.rowColor() )</programlisting>

              <para>And have the <literal>rowColor()</literal> method called
              repeatedly, rather than just once. To avoid that, invoke the
              method outside of the Velocimacro, and pass the value into the
              Velocimacro.</para>

              <programlisting>#set($color = $bar.rowColor())
#foo( $color )</programlisting>
            </answer>
          </qandaentry>

          <qandaentry>
            <question>
              <para>Can I register Velocimacros via
              <literal>#parse</literal>?</para>
            </question>

            <answer>
              <para><emphasis>Yes</emphasis>. Velocimacros may be defined in a file that
              is loaded into a template with <literal>#parse</literal>.  This is especially
              helpful if you wish to have a library of macros used by multiple templates.  
              As an alternative you may also 
              use the <literal>velocimacro.library</literal> facility to have
              Velocity load your Velocimacros at startup.</para>
            </answer>
          </qandaentry>

      <?hard-pagebreak ?>

          <qandaentry>
            <question>
              <para>What is Velocimacro Autoreloading?</para>
            </question>

            <answer>
              <para>There is a property, meant to be used in
              <literal>development</literal>, not production:</para>

              <para><literal>velocimacro.library.autoreload</literal></para>

              <para>which defaults to false. When set to true along
              with</para>

              <para><emphasis>type</emphasis><literal>.resource.loader.cache =
              false</literal></para>

              <para>(where <emphasis>type</emphasis> is the name of the
              resource loader that you are using, such as
              <emphasis>file</emphasis>) then the Velocity engine will
              automatically reload changes to your Velocimacro library files
              when you make them, so you do not have to dump the servlet
              engine (or application) or do other tricks to have your
              Velocimacros reloaded.</para>

              <para>Here is what a simple set of configuration properties
              would look like.</para>

              <programlisting>file.resource.loader.path = templates
file.resource.loader.cache = false
velocimacro.library.autoreload = true</programlisting>

              <para>Activating auto-reload imposes a performance penalty and
              should be turned off in production.</para>
            </answer>
          </qandaentry>
        </qandadiv>
      </qandaset>
    </section>
  </chapter>

  <chapter id="chapter-miscellany">
    <title>Miscellany</title>

    <section id="section-formatting">
      <title>Formatting</title>

      <para>Although VTL in this user guide is often displayed with newlines
      and whitespaces, the VTL shown below</para>

      <programlisting>#set( $fruits = ["apple", "pear", "orange", "strawberry"] )

#foreach( $fruit in $fruits )
  $fruit
#end</programlisting>

      <para>is equally valid as the following snippet:</para>

      <programlisting>Send me #set($foo=["$10 and ","a pie"])#foreach($a in $foo)$a#end please.</programlisting>

      <para>Velocity's behaviour is to gobble up excess whitespace. The
      preceding directive can be written as:</para>

      <programlisting>Send me
#set( $foo = ["$10 and ","a pie"] )
#foreach( $a in $foo )
$a
#end
please.</programlisting>

      <para>or as</para>

      <programlisting>Send me
#set($foo       = ["$10 and ","a pie"])
                #foreach            ($a in $foo )$a
         #end please.</programlisting>

      <para>In each case the output will be the same.</para>
    </section>

      <?hard-pagebreak ?>
n
    <section id="section-math">
      <title>Math</title>

      <para>Velocity has a number of built-in math operators that can be used
      in templates with the <literal>#set</literal> directive. The following
      equations are examples of addition, subtraction, multiplication and
      division, respectively:</para>

      <programlisting>#set( $foo = $bar + 3 )
#set( $foo = $bar - 4 )
#set( $foo = $bar * 6 )
#set( $foo = $bar / 2 )</programlisting>

      <para>When a division operation is performed between two integers, the
      result will be an integer. Any remainder can be obtained by using the
      modulus (<literal>%</literal>) operator.</para>

      <programlisting>#set( $foo = $bar % 5 )</programlisting>
    </section>

      <?hard-pagebreak ?>

    <section id="section-range-operator">
      <title>Range Operator</title>

      <para>The range operator can be used in conjunction with
      <literal>#set</literal> and <literal>#foreach</literal> statements. It
      creates an array of <literal>java.lang.Integer</literal>
      objects:<literal> [n..m]</literal></para>

      <para>Both <literal>n</literal> and <literal>m</literal> must either be
      or produce integers. If <literal>m</literal> is greater than
      <literal>n</literal>, the range will count down:</para>

      <example id="example-ranges-examples">
        <title>Range examples</title>

        <programlisting>## Example 1: 

#foreach( $cnt in [1..5] )
  $cnt
#end

Result: 1 2 3 4 5

## Example 2:

#foreach( $cnt in [2..-2] )
  $cnt
#end 

Result: 2 1 0 -1 -2

## Example 3:

#set( $range = [0..1] )
#foreach( $cnt in $range )
  $cnt
#end

Result: 0 1

## Example 4:

[1..3]

Result: [1..3] This is not a range (not in a #set or #foreach directive)</programlisting>
      </example>

      <note>
        <para>As any other operator, the range operator is only evaluated in
        Velocity directives. This is why example 4 above does not evaluate the
        range operator.</para>
      </note>
    </section>

    <section id="section-string-concatenation">
      <title>String Concatenation</title>

      <para>String concatenation in VTL is a bit tricky, because it depends on
      the context in which a String should be concatenated.</para>

      <para>Concatenating multiple references in the template output is done
      by simply putting them next to each other. The references are evaluated
      and rendered to the output without any blanks between them.</para>

      <example id="example-string-concatenation-in-template-output">
        <title>String concatenation in Template output</title>

        <programlisting>#set( $size = "Big" )
#set( $name = "Ben" )

## Renders as 'The clock is BigBen.'
The clock is $size$name.</programlisting>
      </example>

      <para>To create a new String object that contains the evaluation of one
      or more references, use the <literal>#set</literal> directive and a
      doublequoted string to concatenate the elements.</para>

      <example id="example-string-concatenation-using-set">
        <title>String concatenation using <literal>#set</literal></title>

        <programlisting>#set( $size = "Big" )
#set( $name = "Ben" )

#set($clock = "$size$name" )

## Renders as 'The clock is BigBen.'
The clock is $clock.</programlisting>
      </example>

      <para>In this example, <literal>$clock</literal> is a new String object
      that contains the evaluation results of <literal>$size</literal> and
      <literal>$name</literal>. These can be simple references as shown above
      or more complex elements like property or method references.</para>

      <example id="example-complex-references-and-string-concatenation">
        <title>Complex references and String concatenation</title>

        <programlisting>#set ($monthdays = [1..30])
#set ($description = "Days in April:")

#set ($result = "$description: $monthdays.size()")

## Renders as 'Days in April: 30'
$result</programlisting>
      </example>
    </section>
  </chapter>
</book>
