如何在 velocity 模板中准备一个带有动态数据的 table?

How to prepare a table with dynamic data in velocity template?

我有一个要求,我需要在速度模板中生成动态 table。

我在 java 代码下面 我正在准备哈希图。输入将来自外部应用程序。

public String generateFileFromStringTemplate(HashMap<String, Object> documentContentHashmap, String templateString,TWList list){
         System.out.println("hashmap : "+list.getArraySize());
         TWObject obj=null;
         Map<String, Map<String,String>> mapobj=new HashMap<>();
        try{
          TemplateUtility tutility = new TemplateUtility();
          obj = TWObjectFactory.createObject();
          for (int i = 0; i < list.getArraySize(); i++) {
            obj=(TWObject) list.getUnmodifiableArray().get(i);
            Object[]s=obj.getPropertyNames().toArray();
            Map<String, String> map1=new HashMap<>();
            for (int j = 0; j < obj.getPropertyNames().toArray().length; j++) {
                map1.put(s[j].toString(),(String) obj.getPropertyValue(s[j].toString()));
            }
            mapobj.put("Map"+i, map1);
          }
          documentContentHashmap.put("Map", mapobj);
          StringWriter strWriter = tutility.generateTemplateFromString(documentContentHashmap, templateString);

          String documentBytes = tutility.generateDocsEncodedToBase64Content(strWriter);
          if (documentBytes != null) {
            return documentBytes;
          }
          return null;
        }
        catch (Exception e){
          e.printStackTrace();
          return e.getMessage();
        }
      }
}

下面是我将 documentContentHashmap 传递到速度模板引擎的代码。

StringWriter generateTemplateFromString(HashMap<String, Object> documentContentHashmap, String templateString)
      {
        try
        {
          RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
          Date date = new Date();
          SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_HHmmss");
          String fileName = "StrTemplate_" + sdf.format(date) + ".html";
          StringReader reader = new StringReader(templateString);
          SimpleNode node = runtimeServices.parse(reader, fileName);
          Template template = new Template();
          template.setRuntimeServices(runtimeServices);
          template.setData(node);
          template.initDocument();
          VelocityContext context = new VelocityContext();
          Set<String> sourceKeySet = documentContentHashmap.keySet();
          System.out.println("sourceKeySet : "+sourceKeySet);
          for (String key : sourceKeySet) {
              System.out.println("documentContentHashmap.get(key) : "+documentContentHashmap.get(key));
            context.put(key, documentContentHashmap.get(key));
          }
          StringWriter writer = new StringWriter();
          template.merge(context, writer);
          return writer;
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        return null;
      }

下面是从上面的代码生成的示例数据。

{Map0={interestRate=3, tenor=2 sal, proposedLimit=555, loanType=PL, approvedLimit=556, loanAmount=554, loanRepaymentDate=AAJ}, Map1={interestRate=1, tenor=3 sal, proposedLimit=445, loanType=HL, approvedLimit=446, loanAmount=444, loanRepaymentDate=KAL}}

下面是我的 html,我在其中迭代地图并尝试将以上数据显示为 2 行,但我无法实现,因此所有数据仅显示在一行中。

<html>
<head>
<style type="text/css">

td,th{font-family:Arial, "Helvetica Neue", Helvetica, sans-serif;font-size:12px ;}
.PaymentVoucher{
    font-size:15px;
    text-align:center;
    letter-spacing: 3px;
}
</style>
</head>
<body>
<div>
<table style="width:100%; border: 1px solid #dddddd; font-family: Times New Roman, Times, sans-serif;">
<tr>
    <td  colspan="2">
        <label><b></b></label>
    </td>
    <td style="width:20%;">
    <span>Customer Name : $pvMap.get('customer_name')</span><br/>
    </td>
</tr>
<tr>
    <td style="width:20%;">
    <br />
        <label>Page &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</label><span>1 of 1</span>
    </td>
</tr>
<tr>
    <td colspan="4" class="PaymentVoucher"><b>Loan&nbsp; Details&nbsp;</b></td>
</tr>
<tr>

    <td>
        <label style="width:450px;">Loan Application Date : </label><span>$pvMap.get('application_date')</span>
    </td>
    <td colspan = "3"></td>
</tr>
</table>
<br />
<table  style="width:100%; border: 1px solid #dddddd; font-family: Times New Roman, Times, sans-serif;"> 
  <tr>
        <th>Loan Type</th><th>Loan Amount</th><th>Interest Rate</th><th>Loan Repayment Date</th><th>Tenor</th><th>Proposed Limit</th><th>Approved Limit</th>
  </tr>
  <tr>
    #set($str1="loanType")

    #set($str2="loanAmount")

    #set($str3="interestRate")

    #set($str4="loanRepaymentDate")

    #set($str5="tenor")

    #set($str6="proposedLimit")

    #set($str7="approvedLimit")

    #foreach ($mapEntry in $Map.entrySet())
        #foreach ($map1 in $mapEntry.getValue().entrySet())
            #if($map1.key==$str1)
                <td>$map1.getValue()</td>
            #end
        #end
    #end
    </tr>
</table>
<br />
<br />
<span>Regards,</span><BR/>
<span>Test</span><BR/>
</div>
</body>
</html>

有人可以帮忙吗?提前致谢。

尝试在第一个循环中移动第二个 <tr> 标签(并使用地图 getter 而不是循环条目,这就是地图的用途):

<table  style="width:100%; border: 1px solid #dddddd; font-family: Times New Roman, Times, sans-serif;"> 
  <tr>
        <th>Loan Type</th><th>Loan Amount</th><th>Interest Rate</th><th>Loan Repayment Date</th><th>Tenor</th><th>Proposed Limit</th><th>Approved Limit</th>
  </tr>
    #set($columns = ["loanType", "loanAmount", "interestRate", "loanRepaymentDate", "tenor", "proposedLimit", "approvedLimit"])
    #foreach ($subMap in $Map.values())
    <tr>
        #foreach ($column in $columns)
            <td>$subMap.get($column)</td>
        #end
    </tr>
    #end
</table>