grantmcconnaughey
grantmcconnaughey

Reputation: 10689

Can Velocity handle objects or just variables?

I am working with a velocity template right now and I'd like to know if I can pass in a Customer object or if I need to pass in the values independently?

For example, can I do $customer.name, $customer.title, etc. or do I need to keep doing $name, $title, etc? Thanks!

Upvotes: 0

Views: 872

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96385

Check out the Velocity user guide, there is a section on methods where it shows the different ways to call methods on an object:

Methods

A method is defined in the Java code and is capable of doing something useful, like running a calculation or arriving at a decision. Methods are references that consist of a leading "$" character followed a VTL Identifier, followed by a VTL Method Body. A VTL Method Body consists of a VTL Identifier followed by an left parenthesis character ("("), followed by an optional parameter list, followed by right parenthesis character (")"). These are examples of valid method references in the VTL:

$customer.getAddress() $purchase.getTotal() $page.setTitle( "My Home Page" ) $person.setAttributes( ["Strange", "Weird", "Excited"] )

and following that is a section on referencing object properties:

Property Lookup Rules

As was mentioned earlier, properties often refer to methods of the parent object. Velocity is quite clever when figuring out which method corresponds to a requested property. 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 $customer.address, the sequence is

getaddress()
getAddress()
get("address")
isAddress()

For upper-case property names like $customer.Address, it is slightly different:

getAddress()
getaddress()
get("Address")
isAddress()

so yes, you can put objects in the Velocity context and refer to their fields.

Upvotes: 3

Related Questions