如何正确评估Velocity上下文?

问题描述

我是Apache Velocity的新手,我想知道什么是评估上下文的正确方法。这是我的情况:

我想打开一个用作模板的.docx文件,用Apache Velocity替换其中的一些单词,然后将结果保存到新的.docx文件中。为此,我的代码如下:

    public static void main(String[] args) {

    Velocity.init();

    final VelocityContext context = new VelocityContext();
    context.put("city","Firenze");
    context.put("user","Federico");
    context.put("date","23/09/20");
    context.put("op","Mario Rossi");
    ArrayList<String> list = new ArrayList<String>();
    list.add("Data futura");
    list.add("Scrittura indecifrabile");
    context.put("list",list);

    String name = "tempWord.docx";
    List<XWPFParagraph> paragraphs;

    try {
        paragraphs = readDocxFile(name);
        XWPFDocument doc = new XWPFDocument();
        final FileOutputStream fos = new FileOutputStream(new File("outFile.docx"));

        for(XWPFParagraph para : paragraphs) {
            StringWriter sw = new StringWriter();
            System.out.println(para.getText());
            Velocity.evaluate(context,sw,"test1",para.getText());
            XWPFParagraph par = doc.createParagraph();
            XWPFRun run = par.createRun();
            run.setText(sw.toString());
        }
        doc.write(fos);
        fos.close();

    } catch(Exception rnfe) {
        rnfe.printStackTrace();
    }

}

其中readDocxFile()是我已经定义并且可以完美工作的方法。给我担心的是给定此模板:

    ${city},${date}

    Gentile ${user},Con la seguente la informiamo che non abbiamo potuto processare la sua richiesta a causa dei seguenti errori:
    #foreach(${name} in ${list})
        ${name}
    #end
    La preghiamo dunque di correggere e sottoporre nuovamente il modulo entro e non oltre la data di scadenza.
    Cordiali saluti,${op}

我收到此错误

    1606 [main] ERROR org.apache.velocity.parser - test1: Encountered "<EOF>" at line 1,column 29.

它在解析#foreach循环时发生,并且似乎与Velocity.evaluate()方法有关,因为如果我创建一个tmp.txt文件并将其与Velocity模板一起用作Velocity模板, Velocity.mergeTemplate()方法使代码正确运行。这种方法的问题在于,我不想每次都要评估上下文时都存储.txt,而必须保持原始文件格式。

据我了解,evaluate()逐行评估,因此显然#foreach块评估不正确。

我知道Apache POIdocx4j一样也可以执行上下文替换,但是我必须使用Velocity。

如何正确评估上下文?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)