2016-08-11 2 views
0

У меня есть требование, в котором я должен установить данные в html-файле, используя шаблон скорости. Я должен динамически создавать таблицу, а также показывать некоторые статические данные. Я могу динамически устанавливать данные в таблицу, но я не могу получить статические данные из своего списка. Моя проблема в том, что я должен извлекать как динамические, так и статические данные только из одного списка.Мне нужно установить данные в html-файл, используя шаблон скорости?

код Скорость:

public static String prepareTemplate(HashMap<String, String> documentContentHashmap,String templateLocation) throws NamingException{ 
    System.out.println("Document Contents :"+documentContentHashmap); 
    ArrayList documentList=new ArrayList(); 
    documentList.add(documentContentHashmap); 
    System.out.println(documentList); 
    String templatePath=templateLocation.replaceAll("\\\\","/"); 
    String[] splittedTemplatePath = templatePath.split("/"); 
    String templateName=splittedTemplatePath[splittedTemplatePath.length-1]; 
    VelocityEngine ve = new VelocityEngine(); 
    Properties properties = new Properties(); 
    properties.setProperty("resource.loader","file"); 
    properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); 
    properties.setProperty("file.resource.loader.path", templatePath.substring(0, templatePath.lastIndexOf("/"))+"/");   
    properties.setProperty("file.resource.loader.cache", "false"); 
    properties.setProperty("file.resource.loader.modificationCheckInterval", "0"); 
    ve.init(properties); 
    Template t = ve.getTemplate(templateName); 
    VelocityContext context = new VelocityContext(); 
    //for (Entry<String, String> entry : documentContentHashmap.entrySet()) { 
     //context.put(entry.getKey(), entry.getValue()); 
    //} 
    context.put("documentList", documentList); 
    StringWriter writer = new StringWriter(); 
    t.merge(context, writer); 
    System.out.println("writer"+writer); 
    String documentBytes=generateDocument(writer); 
    if(documentBytes!=null){ 
     return documentBytes; 
    }else{ 
     return null; 
    } 
} 

Html файл:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="ISO-8859-1"/> 
<title>Payment Voucher</title> 
</head> 
<body> 
<div id="container"> 
    <div id="leftDiv"> 
     <img alt="logo" src="$image_path"/> 
    </div> 
    <br/> 
    <div id="rightDiv" style="align:right;"> 
     <label>Invoice Number :</label>&nbsp;&nbsp;&nbsp;<span>Here i have to access some value from the same documentList </span><br/> 
     <label>Invoice Date :</label>&nbsp;&nbsp;&nbsp;<span>Here i have to access some value from the same documentList </span> 
    </div> 
    <table> 
    #foreach($documentContent in $documentList) 
     <tr><td>$documentContent.invoice_no</td></tr> 
    #end 
    </table> 
</div> 
</body> 
</html> 

ответ

0

Вместо создания ArrayList использовать HashMap непосредственно. Контекст Velocity может принимать любой тип объекта, а функции, доступные на Карте, будут доступны внутри шаблона.

context.put("documentList", documentList);

становится

context.put("documentList", documentContentHashmap);

Используйте его в шаблоне, как

<div id="rightDiv" style="align:right;"> 
    <label>Invoice Number :</label><span>access from documentList: $documentList.get("key1") </span><br/> 
    <label>Invoice Date :</label><span>access from documentList: $documentList.get("key2") </span> 
</div> 

Ваш код Итерация остается тем же. В случае, если вы хотите обеспечить порядок итерации, используйте LinkedHashMap

Смежные вопросы