I have a class CurrencyUtil
in which I have written a method convertCurrency(String symbol, long value)
I want to call this method from velocity template. I am putting object of this class map.put("formatter", currencyUtil);
and in template I am using the tag as $formatter.convertCurrency($currency, $total)
but when the template is rendered it is not printing the result.
here my question is that, should the parameter names in the java method and in template be same? or is there any other problem?
You can test Velocity templates in your web application by integerating Cactus with VelocityViewServlet. This assumes that you are running your web application at http://localhost:8080/CactusDemo/ .
Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code.
1 answer. Or in your Java code, try: URL url = new URL("image. png");
Parameter names in java method and template can be different. You may try to locate your problem using the following example.
Example.java
package com.example.currency;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import java.io.*;
public class Example
{
public Example(String templateFile)
{
try
{
Velocity.init("velocity.properties");
VelocityContext context = new VelocityContext();
CurrencyUtil cu = new CurrencyUtil();
cu.setCurrencyRate("EUR", 1.25);
context.put("formatter", cu);
Template template = null;
try
{
template = Velocity.getTemplate(templateFile);
}
catch( ResourceNotFoundException rnfe )
{
System.out.println("Example : error : cannot find template " + templateFile );
}
catch( ParseErrorException pee )
{
System.out.println("Example : Syntax error in template " + templateFile + ":" + pee );
}
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(System.out));
if ( template != null)
template.merge(context, writer);
writer.flush();
writer.close();
}
catch( Exception e )
{
System.out.println(e);
}
}
public static void main(String[] args)
{
Example t = new Example("example.vm");
}
}
CurrencyUtil.java
package com.example.currency;
import java.util.Map;
import java.util.HashMap;
public class CurrencyUtil {
private static Map<String, Double> rates = new HashMap<String, Double>();
public double getCurrencyRate(String symbol){
return rates.get(symbol);
}
public void setCurrencyRate(String symbol, double currencyRate){
rates.put(symbol, currencyRate);
}
public double convertCurrency(String symbol, long value){
return value * getCurrencyRate(symbol);
}
}
example.vm
#set( $total = 10000000000)
#set( $currency = "EUR")
$formatter.convertCurrency($currency, $total)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With