Apache velocity template file


















There are quite a few resources and examples available to the programmer, and we recommend that you look at our examples, documentation and even the source code.

Some great sources are:. When using Velocity in an application program or in a servlet or anywhere, actually , you will generally do the following:. In code, using the singleton pattern via the org. Velocity class, this looks like. That's the basic pattern. It is very simple, isn't it? This is generally what happens when you use Velocity to render a template.

You probably won't be writing code exactly like this - we provide a few tools to help make it even easier. However, no matter how to use Velocity the above sequence is what is happening either explicitly, or behind the scenes.

Developers have two options for using the Velocity engine, the singleton model and the separate instance model. The same core Velocity code is used for both approaches, which are provided to make Velocity easier to integrate into your Java application.

This is the legacy pattern, where there is only one instance of the Velocity engine in the JVM or web application, depending that is shared by all. This is very convenient as it allows localized configuration and sharing of resources.

For example, this is a very appropriate model for use in a Servlet 2. The singleton is accessable via the org. Velocity class, and and example of use:. New in version 1. This is useful when you wish to support separate configurations, such as template directories, loggers, etc in the same application. To use separate instances, use the org. VelocityEngine class. An example, which parallels the above singleton example, looks like:.

As you can see, this is very simple and straightforward. Except for some simple syntax changes, using Velocity as a singleton or as separate instances requires no changes to the high-level structure of your application or templates. As a programmer, the classes you should use to interact with the Velocity internals are the org. Velocity class if using the singleton model, or org. VelocityEngine if using the non-singleton model 'separate instance'.

As mentioned above, the classes you should use are located in the org. If anything is missing or needed from those classes, do not hesitate to suggest changes - these classes are intended for the application developer. The concept of the 'context' is central to Velocity, and is a common technique for moving a container of data around between parts of a system. The idea is that the context is a 'carrier' of data between the Java layer or you the programmer and the template layer or the designer.

You as the programmer will gather objects of various types, whatever your application calls for, and place them in the context. To the designer, these objects, and their methods and properties, will become accessable via template elements called references. Generally, you will work with the designer to determine the data needs for the application. In a sense, this will become an 'API' as you produce a data set for the designer to access in the template.

Therefore, in this phase of the development process it is worth devoting some time and careful analysis. While Velocity allows you to create your own context classes to support special needs and techniques like a context that accesses an LDAP server directly, for example , a good basic implementation class called VelocityContext is provided for you as part of the distribution. VelocityContext is suitable for all general purpose needs, and we strongly recommended that you use it.

Only in exceptional and advanced cases will you need to extend or create your own context implementation. Using VelocityContext is as simple as using a normal Java Hashtable class. While the interface contains other useful methods, the two main methods you will use are. Please note that like a Hashtable, the value must be derived from java.

Object, and must not be null. Fundamental types like int or float must be wrapped in the appropriate wrapper classes. That's really all there is to basic context operations. For more information, see the API documentation included in the distribution.

As a programmer, you have great freedom in the objects that you put into the context. But as with most freedoms, this one comes with a little bit of responsibility, so understand what Velocity supports, and any issues that may arise. Velocity supports serveral types of collection types suitable for use in the VTL foreach directive:.

In the case of the Iterator and Enumeration , it is recommended that they are placed in the context only when it cannot be avoided, and you should let Velocity find the appropriate reusable iterative interface when that is sufficient and possible. There are good reasons to use the java.

Iterator interface directly large data sets via JDBC, for example , but if it can be avoided, it might be better to use something else. By 'directly' , we meant doing something like:. With just a plain Iterator the first snippet above The result is no output from any subsequent foreach blocks using that reference. This above isn't meant to give the impression that iterating over collections in Velocity is something that requires great care and thought.

Rather, the opposite is true, in general. Just be careful when you place an Iterator into the context. Not all classes are instantiable. Classes like java. Math do not provide any public constructor, and yet may contain useful static methods.

In order to access these static methods from a template, you can simply add the class itself to the context:. This will allow you to call any public static method in java.

An innovative feature of Velocity's context design is the concept of context chaining. Also sometimes referred to as context wrapping , this advanced feature allows you to connect separate contexts together in a manner that makes it appear as one 'contiguous' context to the template. In the code above, we have set up context2 such that it chains context1. This means that in the template, you can access any of the items that were put into either of the two VelocityContext objects, as long as there is no duplication of the keys used to add objects.

If that is the case, as it is above for the key 'duplicate', the object stored in the nearest context in the chain will be available.

In this example above, the object returned would be the string "I am in context2". Note that this duplication, or 'covering', of a context item does not in any way harm or alter the covered object. So in the example above, the string "I am in context1" is alive and well, still accessable via context1. Note also that you have to be careful when you are relying on the template to add information to a context that you will examine later after the rendering.

The changes to the context via set statements in a template will affect only the outer context. So make sure that you don't discard the outer context, expecting the data from the template to have been placed onto the inner one. This feature has many uses, the most common so far is providing layered data access and toolsets. As mentioned before, the Velocity context mechanism is also extendable, but beyond the current scope of this guide.

If you are interested, please see the classes in the package org. There are two common situations where the Java code must deal with objects created at runtime in the template:.

When a template adds objects to the context, the Java code can access those objects after the merge process is complete. One of the features provided by the VelocityContext or any Context derived from AbstractContext is node specific introspection caching.

Generally, you as a the developer don't need to worry about this when using the VelocityContext as your context. However, there is currently one known usage pattern where you must be aware of this feature.

The Apache projects are characterized by a collaborative, consensus based development process, an open and pragmatic software license, and a desire to create high quality software that leads the way in its field.

If you came here because you heard about Velocity somewhere on the web, this is probably the right place to start. You will find e. Velocity will parse the VTL and render the template specified.

Like the include directive, parse can take a variable rather than a template. Unlike the include directive, parse will only take a single argument.

VTL templates can have parse statements referring to templates that in turn have parse statements. By default set to 10, the directive. Note: 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 reduces the need to redefine the Velocimacro on numerous templates, saving work and reducing the chance of error, and ensures that a single change to a macro available to more than one template.

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. 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. 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. 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:. Web designers create HTML pages with placeholders for dynamic information. The page is processed with VelocityViewServlet or any of a number of frameworks which support Velocity. Source code generation.

The PoweredByVelocity page lists a number of open source and commercial development software packages which use Velocity in this manner. Automatic emails. Many applications generate automatic emails for account signup, password reminders or automatically sent reports. Using Velocity, the email template can be stored in a text file rather than directly embedded in your Java code.

XML transformation.



0コメント

  • 1000 / 1000