The Apache Velocity templating engine (or short Velocity is a template engine manual, the Velocity Developers Guide, which describes how to integrate. Velocity Template Language (VTL): An Introduction. .. This manual should help you get started with Velocity and the Velocity Template Language. It has a. Velocity Template Language (VTL): An Introduction; Hello Velocity World! The Velocity User Guide is intended to help page designers and content If you encounter any mistakes in this manual or have other feedback related to the.

Apache Velocity Tutorial Pdf

Language:English, Arabic, Dutch
Genre:Children & Youth
Published (Last):27.12.2015
ePub File Size:20.63 MB
PDF File Size:20.62 MB
Distribution:Free* [*Registration Required]
Uploaded by: JENETTE

Learn the main features of Apache Velocity and explore how it can be used to create dynamic web pages in a Velocity is a Java-based templating engine. .. The complete code for this tutorial is available over on GitHub. DVSL. Velocity Generator. Velocity UI for Eclipse. Tutorials. Template-Based Wizards in JBuilder. Start Up the Velocity Template Engine. Velocity Template Language (VTL): An Introduction. .. located at http://velocity. longmogedwapor.cf What is Velocity?.

You use the same general process to create a Velocity-based application as you would any application. Let's consider a more interesting example than the Hello World application above. Suppose you operate a pet store and wish to generate an email blast to announce a sale. First, you must design the email and then develop the template and code based on that design. For this example, let's suppose you decide on three pets for sale, each with a different advertised price.

You decide to use a map to associate each pet name and its price, and then store all three maps in a list. You call this list petList , the pet name name , and the price as price in the map.

Now that you have identified the relevant data, its representation, and naming criteria, you can write the code and the template's design. Once you agree on data specifics, Velocity lets you write the code and design the template in parallel. The designer integrates the data into the nondata presentation content like images, text, and so on in the template. In this case, we simply write in the email body:. Modeled after a java. Map , the context is an object that holds data provided by the application or servlet that the template accesses.

Your Answer

For this example, we get all the data from our data sources in this case, we hardwire it into the code , organize it, and add it to the context:.

Now, with the data organized and placed in the context and the template ready, we can render the template against the context. Here is the code:. This complete program generates your email body. Because Velocity renders templates into a Writer , you can easily manage the output. In this case, the rendered output went into a String via the StringWriter , but it could easily have gone to a file, a browser, or a BLOB binary large object in a database. This is one reason why Velocity integrates so easily into Java applications.

I've shown Velocity templates for two different examples, but in neither case have I explained what the special markup did although you could probably guess. Described as "a language definition with a feature set that fits comfortably on a standard business card" see Jim Jagielski's " Getting Up to Speed with Velocity " VTL has been intentionally kept simple and small by the community.

References in the template access data. They freely mix with the template's non-VTL content. If no corresponding data object exists in the context, the template simply treats the reference as text and renders it as-is into the output stream. The Velocity reference allows access to any object's public method, and the template's syntax is the same as it would be in Java code.

Here are a few examples:. You may recall from the Pet Store email example that we stored the name and price information in a java. Map , and accessed the data using two tokens name and price , which don't exist as methods in the java. Map class:. This works because Velocity incorporates a JavaBean-like introspection mechanism that lets you express method accesses in references using a property notation.

In the Pet Store example template, Velocity's introspection facility finds and invokes the Map 's public Object get String method with the keys name and price.

Velocity - An Introduction

We could access the same data in a different way by invoking the get String method directly in the template:. This would produce the same output, and better represents what is actually happening. However, the other way that uses the property notation is easier to read and doesn't tie your template to the data class's specific implementation. For example, you can replace the Map in the List with a class that has public methods getName and getPrice , and the original example template containing the following will continue to work:.

If the directive. Recursion is permitted, for example, if the template dofoo. After "Count down. When the count reaches 0, it will display the "All done with parsefoo.

At this point, Velocity will return to dofoo. The break directive stops any further rendering of the current execution scope. An "execution scope" is essentially any directive with content i.

Unlike stop, break will only stop the innermost, immediate scope, not all of them. If you wish to break out of a specific execution scope that is not necessarily the most immediate one, then you can pass the scope control reference i. This will stop rendering of all scopes up to the specified one. The stop directive stops any further rendering and execution of the template.

This is true even when the directive is nested within another template accessed through parse or located in a velocity macro. The resulting merged output will contain all the content up to the point the stop directive was encountered. This is handy as an early exit from a template.

For debugging purposes, you may provide a message argument e. The evaluate directive can be used to dynamically evaluate VTL.

This allows the template to evaluate a string that is created at render time.

Such a string might be used to internationalize the template or to include parts of a template from a database. The macro script element allows template designers to define a repeated segment of a VTL template.

Velocimacros are very useful in a wide range of scenarios both simple and complex. This Velocimacro, created for the sole purpose of saving keystrokes and minimizing typographic errors, provides an introduction to the concept of Velocimacros.

The Velocimacro being defined in this example is d , and it can be called in a manner analogous to any other VTL directive:. When this template is called, Velocity would replace d with a row containing a single, empty data cell. If we want to put something in that cell, we can alter the macro to allow for a body:. A Velocimacro can also take any number of arguments -- even zero arguments, as demonstrated in the first example, is an option -- but when the Velocimacro is invoked, it must be called with the same number of arguments with which it was defined.

Many Velocimacros are more involved than the one defined above. Here is a Velocimacro that takes two arguments, a color and an array.

The Velocimacro being defined in this example, tablerows , takes two arguments. Anything that can be put into a VTL template can go into the body of a Velocimacro. The tablerows Velocimacro is a foreach statement. There are two end statements in the definition of the tablerows Velocimacro; the first belongs to the foreach , the second ends the Velocimacro definition.

When the tablerows Velocimacro is called in this situation, the following output is generated:. Velocimacros can be defined inline in a Velocity template, meaning that it is unavailable to other Velocity templates on the same web site.

Defining a Velocimacro such that it can be shared by all templates has obvious advantages: It could be used many times and for many different purposes.

In the template mushroom. When fulfilling a request for mushroom. When passing references as arguments to Velocimacros, please note that references are passed 'by name'. This means that their value is 'generated' at each use inside the Velocimacro.

This feature allows you to pass references with method calls and have the method called at each use. For example, when calling the following Velocimacro as shown. At first glance, this feature appears surprising, but when you take into consideration the original motivation behind Velocimacros -- to eliminate cut'n'paste duplication of commonly used VTL -- it makes sense.

It allows you to do things like pass stateful objects, such as an object that generates colors in a repeating sequence for coloring table rows, into the Velocimacro.

If you need to circumvent this feature, you can always just get the value from the method as a new reference and pass that:. Several lines in the velocity. Note that these are also documented in the Developer Guide. By default, Velocity looks for a single library: The configured template path is used to find the Velocimacro libraries.

The default, true, allows template designers to define Velocimacros in the templates themselves. The default, false , prevents Velocimacros defined inline in a template from replacing those defined in the template libraries loaded at startup. 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. 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 off in the resource loaders e. This feature is intended for development, not for production. Please note than when two templates each define a macro with the same name, you either need velocimacro.

This section deals with escaping these characters. There is no problem writing "I bought a 4 lb. Cases may arise where you do not want to have a reference rendered by Velocity. There are a few ways of doing this, but the simplest is to use the escape character.

Here is a demonstration:. Notice Velocity handles references that are defined differently from those that have not been defined. The output will be: Sometimes Velocity has trouble parsing your template when it encounters an "invalid reference" that you never intended to be a reference at all.

Escaping special characters is, again, the best way to handle these situations, but in these situations, the backslash will likely fail you. Or, if you are using VelocityTools , you can just use the EscapeTool like this:. Escaping of both valid and invalid VTL directives is handled in much the same manner; this is described in more detail in the Directives section. Extra care should be taken when escaping VTL directives that contain multiple script elements in a single directive such as in an if-else-end statements.

Here is a typical VTL if-statement:. Escaping script elements alters the output. Consider the following case:.

To understand this, note that the if arg when ended by a newline return will omit the newline from the output. Here the if is escaped, but there is an end remaining; having too many endings will cause a parsing error. Velocity's default behaviour is to gobble up excess whitespace. The preceding directive can be written as:.

Introduction to Apache Velocity

In each case the output will be the same. Please note that it's possible to configure Velocity with other space gobbling behaviors. Velocity has a handful of built-in mathematical functions that can be used in templates with the set directive.

The following equations are examples of addition, subtraction, multiplication and division, respectively:. When a division operation is performed between two integers, the result will be an integer, as the fractional portion is discarded.

The range operator can be used in conjunction with set and foreach statements. Useful for its ability to produce an object array containing integers, the range operator has the following construction:.

Both n and m must either be or produce integers. Whether m is greater than or less than n will not matter; in this case the range will simply count down. Examples showing the use of the range operator as provided below:.

Note that the range operator only produces the array when used in conjunction with set and foreach directives, as demonstrated in the fourth example.

Web page designers concerned with making tables a standard size, but where some will not have enough data to fill the table, will find the range operator particularly useful. When a reference is silenced with the! This section is a mini-FAQ on topics relating to Velocimacros. This section will change over time, so it's worth checking for new information from time to time. A directive isn't a valid argument to a directive, and for most practical purposes, a VM is a directive.

One easy solution is to take advantage of the fact that 'doublequote' " renders its contents. So you could do something like. Please note that in the latter example the arg is evaluated inside the VM, not at the calling level. In other words, the argument to the VM is passed in in its entirety and evaluated within the VM it was passed into. This allows you to do things like:. This is an intentional and jealously guarded feature - args are passed 'by name' into VMs, so you can hand VMs things like stateful references such as.

Setting this option to 0 will turn checking off. A Velocity template is simply an HTML document with some special placeholders that Velocity will recognize and replace with data you supply in your Java program. For our simple test, we have a template named hello.

It is standard practice to name Velocity templates with the extension of vm. Let's look at a Velocity Servlet. Template; import org. VelocityServlet; import org. Velocity; import org. Context; import javax. We override the handleRequest method which will be invoked when the Servlet is executed. We will place the data we wish to use to fill the placeholders with into the Context object. We must return a Template object. In our example, we are returning the template that we created above.

Using a Java Class in a Template That was simple so now let's look at something a little more complex. Although we could fill our Context object with separate Strings for each placeholder, this isn't always required. We could create a Java class with the appropriate get methods and pass that to our template. Let's create a simple Customer class to use in our example. The class has set and get methods that we can use to access the private Customer variables. It then returns the customer template.

How does the customer template access the data from the Customer object? The answer is that we use a simple dot notation. Do you notice what is missing from the template?Velocity Template Language I've shown Velocity templates for two different examples, but in neither case have I explained what the special markup did although you could probably guess. Overriding few properties can change this location:. However, the other way that uses the property notation is easier to read and doesn't tie your template to the data class's specific implementation.

At the Jakarta Velocity Project Website, where you can download the freely available source code, a thriving and growing community of users is ready to answer questions and offer solutions to common templating problems. This would produce the same output, and better represents what is actually happening. The complete code for this tutorial is available over on GitHub. The second is a corresponding Java program called HelloWorld. StringWriter; import java.

You call this list petList, the pet name name, and the price as price in the map. The flexibility of Velocity is enormous and limited only by your creativity.

NOVELLA from Riverside
I do like reading novels silently . Feel free to read my other articles. I have a variety of hobbies, like fastnet.