【问题标题】:How to ignore missing parameters in Groovy's template engine如何忽略 Groovy 模板引擎中缺少的参数
【发布时间】:2017-05-17 12:39:29
【问题描述】:

我有一个带有占位符的模板(例如 ${PARAM1}),程序成功地解决了它们。但是,如果我只想解析传递给模板引擎的占位符并忽略其他 ${} 该怎么办?目前,如果程序无法解析所有占位符,则会失败。

static void main(String[] args) {

    def template = this.getClass().getResource('/MyFile.txt').text

    def parameters = [
        "PARAM1": "VALUE1",
        "PARAM2": "VALUE2"
    ]
    def templateEngine = new SimpleTemplateEngine()
    def output = templateEngine.createTemplate(template).make(parameters)
    print output
}

文件:${PARAM1} ${PARAM2} ${PARAM3}

谢谢

【问题讨论】:

  • 你能写出预期的输出吗?
  • 预期输出:VALUE1 VALUE2 ${PARAM3}
  • 老实说,我不确定 groovy 模板引擎是否支持忽略参数的方式;但是您可以将您的参数更改为:def parameters = [ "PARAM1": "VALUE1", "PARAM2": "VALUE2", "PARAM3": "\${PARAM3}" ] 这将为您提供预期的输出。
  • 我刚试过,它有效。但是我需要生成大型构建脚本并且只解决部分占位符的问题 - 并且两次编写所有占位符很无聊)。可能我会尝试使用freemarker
  • 你有地图形式的参数我可以帮你自动放置占位符

标签: groovy template-engine


【解决方案1】:

老实说,我不确定 groovy 模板引擎是否支持忽略参数的方式; (在缺少相应的参数时保留占位符)但这是一个技巧。

import groovy.text.*;

def template = "\${PARAM1} \${PARAM2} \${PARAM3} \${PARAM4} \${PARAM5} \${PARAM6}"

//example hard coded params; you can build this map dynamically at run time
def parameters = [
    "PARAM1": "VALUE1",
    "PARAM2": "VALUE2",
    "PARAM3": null,
    "PARAM4": "VALUE4",
    "PARAM5": null,
    "PARAM6": "VALUE6"
]

//this is the hack
parameters.each{ k, v ->
   if(!v){
        parameters[k] = "\$$k"
    }
}


def templateEngine = new SimpleTemplateEngine()
def output = templateEngine.createTemplate(template).make(parameters)
print output

输出:

VALUE1 VALUE2 $PARAM3 VALUE4 $PARAM5 VALUE6

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2014-12-24
    相关资源
    最近更新 更多