velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
Subject Re: Noob Question about Object Access
Date Wed, 24 Oct 2007 07:50:11 GMT
Hi Tyler,

to instantiate new object in Velocity, it is recommended to use a tool placed/accessible in
the context. This is either done from the servlet, or using the ToolboxManager from the VelociityViewServlet.
For both of these approaches you need the webservice container access/control.

The tool may be any simple public java class, something in the line of:

public MoneyTool
  public MoneyTool()
    // a constructor to instantiate the tool
  public MoneyImpl create(String bigDecimal, String unit)
    BigDecimal upperAmount = new BigDecimal(bigDecimal);
    return new MoneyImpl(upperAmount, unit);

And then use it in the template:
#set( $upperBound = MoneyTool.create("1500.00", "USD") )
#if( $price.lessThan($upperBound) && $price.greaterThan($lowerBound) )

Alternatively you can use hidden velocity capabilities to instantiate random objects, as in:
This combined with some macros allows creating readable code.
DISCLAIMER: The velocity authors do not recommend using getClass().forName(...).newInstance()
in the template, which is against the MVC paradigm, and since the servers might have this
feature blocked by an ueberspector, more here:
You should, when possible use tools placed in the context in the servlet side.

Hope this helps,

Tyler Kremberg wrote:
> Please ignore my ignorance, I've read through the documentation and haven't
> figured out how to solve my problem.  ; I am a front-end developer coming
> from the PHP world with only some JSP background.  I am working on a system
> that I do not have the source to.  Anyway, I have access to price
> information.
> #set ($productPrice = $product.getPrice($sesShoppingCart.getCurrency()))
> #set ($listPrice = $price.getAmount())
> I even have access to a Class with comparator methods.
> I need to do something like this: 
> #if( $price.lessThan($upperBound) && $price.greaterThan($lowerBound) )
>    Hooray!
> #end
> In JSP, I could write a scriptlet.
> BigDecimal upperAmount = new BigDecimal("1500.00");
> $upperBound = new MoneyImpl(upperAmount, "USD");
> My question, how can I create the $upperBound and $lowerBound as Money
> objects in the scope of this template.  What is the best way to do this in
> Velocity?  Am I barking up the wrong tree?
> Help is greatly appreciated.  Thanks!
> Tyler
> P.S. For reference, class documentation:
> tml#greaterThan(com.elasticpath.domain.misc.Money)
> neyImpl.html
> ---------------------------------------------------------------------
> To unsubscribe, e-mail:
> For additional commands, e-mail:

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message