Velocity template call java method




















Add a Lesson. Edit a Lesson. Do you want to delete selected author from your authors list. You have to do Login for More! Read, Write and Share your books with Friends and World. Books as your favorite books. Write your own notes and keep it with you ever. Books of Venkatesan. Don't lose your learnings hereafter. Save and revise it whenever required. Click here for more details. John Peter Pune, Maharashtra, India.

Add as Author. Share Link. MacroVTLExample import java. Java Apache Velocity Examples. Lesson Name. 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.

The Velocity Template Language VTL is a simple syntax providing two parts: references, a formalism for accessing objects in the context; and directives, a set of statements used for control and action. 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.

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:. Here are the latest Insider stories. 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:. 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 behaviour is to gobble up excess whitespace. The preceding directive can be written as:. 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.



0コメント

  • 1000 / 1000