Reputation: 417
I have couple of #foreach #if combinations in my velocity template after marge the template I am facing formatting issues as below:
template:
#if ($rq.allowanceType == "TAXI")
#foreach($i in [1..50])
#set($test = "$rq.subType$i")
#if($render.eval($ctx, "$rq.subType$i") != "" && $test != $render.eval($ctx, "$rq.subType$i"))
<aps:lineItem>
<aps:details>
<aps:type>$render.eval($ctx, "$rq.type$i")</aps:type>
<aps:billNumber>$render.eval($ctx, "$rq.billNumber$i")</aps:billNumber>
<aps:isReceived>$render.eval($ctx, "$rq.valid$i")</aps:isReceived>
#if($render.eval($ctx, "$rq.valid$i") == "YES")
<aps:FromDate>$render.eval($ctx, "$rq.FromDate$i")</aps:FromDate>
<aps:ToDate>$render.eval($ctx, "$rq.ToDate$i")</aps:ToDate>#end#if($render.eval($ctx, "$rq.Amount$i") != "")<aps:Amount>$render.eval($ctx, "$rq.Amount$i")</aps:Amount>#end#if($render.eval($ctx, "$rq.VatAmount$i") != "")<aps:VatAmount>$render.eval($ctx, "$rq.VatAmount$i")</aps:VatAmount>
#end
<aps:GrossAmount>$render.eval($ctx, "$rq.GrossAmount$i")</aps:GrossAmount>
</aps:details>
</aps:lineItem>
#end
#end
#end
Formatting as
<aps:lineItem>
<aps:details>
<aps:type>FRAMES</aps:type>
<aps:billNumber>695</aps:billNumber>
<aps:isReceived>YES</aps:isReceived>
<aps:FromDate>01/02/1993</aps:FromDate>
<aps:ToDate>01/02/1994</aps:ToDate> <aps:GrossAmount>3000</aps:GrossAmount>
</aps:details>
</aps:lineItem>
<aps:lineItem>
<aps:details>
<aps:type>TEST</aps:type>
<aps:billNumber>695</aps:billNumber>
<aps:isReceived>NA</aps:isReceived>
<aps:GrossAmount>3000</aps:GrossAmount>
</aps:details>
</aps:lineItem>
What should we have to take care while adding conditions and loops in velocity template so that it will not create formatting issues?
Upvotes: 0
Views: 1010
Reputation: 935
you can try quick-templates to get XML/JSON templating capability
offers better capabilities than apache velocity
IEngine templateEngine=EngineFactory.getInstance().getEngine(EngineType.TEMPLATES);
templateEngine.initialize("/com/tester/template-rules-config.xml");
long startTime=System.currentTimeMillis();
EngineResponse response=templateEngine.execute(context);
Upvotes: 0
Reputation: 2702
Unfortunately velocity doesn't make it easy to keep the formatting of the output nice and clean while having good looking templates at the same time.
An easy workaround is not to care about the output of velocity. In your case, since you're generating xml, apply an xml-beautifier after velocity creates the file, e.g. you can use the one from xmlbeans which can be easily used programmatically:
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
public static void beautify(File xmlFile) {
XmlOptions options = new XmlOptions();
options.setLoadLineNumbers();
XmlObject doc = XmlObject.Factory.parse(xmlFile, options);
options = new XmlOptions();
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(4);
doc.save(xmlFile, options);
}
Upvotes: 1