简体   繁体   English

如果值为空,则保留 FreeMarker 标记

[英]Preserving FreeMarker Markup if value is null

So I'm currently trying to figure out if there is anyway to preserve the freemarker markup if the data model provided doesn't contain that value.所以我目前正试图弄清楚如果提供的数据模型不包含该值,是否还有保留freemarker标记的方法。 I know about ${VALUE!"DEFAULTVALUE"} , but that does not work with FreeMarker markup.我知道${VALUE!"DEFAULTVALUE"} ,但这不适用于 FreeMarker 标记。

Essentially, what I'm trying to do is something along the lines of:从本质上讲,我正在尝试做的事情是这样的:

${TEST}${1}${2}

If the data model is set up as the following:如果数据模型设置如下:

Map root = new HashMap();
root.put("1","ONE");
root.put("2","TWO");

When this is applied to the Template object, a null error is thrown because test is undefined.当这应用于 Template 对象时,会抛出null错误,因为 test 未定义。 What I'm trying to get happen is if TEST is undefined, the template should still be processed into the following:我想要发生的是,如果TEST未定义,模板仍应处理为以下内容:

${TEST}ONETWO

Is there any way to do this using features in the FreeMarker library?有没有办法使用FreeMarker库中的功能来做到这一点? I can do this with pattern matching, but there must be an easier way.我可以通过模式匹配来做到这一点,但必须有更简单的方法。

Thanks.谢谢。

Try using ?has_content for TEST , maybe that will help.尝试使用?has_content进行TEST ,也许这会有所帮助。 But I am not sure, if that suits to your requirements.但我不确定这是否符合您的要求。

The FreeMarker library allows you to write a custom exception handler. FreeMarker 库允许您编写自定义异常处理程序。

Unfortunately FreeMarker doesn't give the exact token that fails but you can work it out from the error message.不幸的是,FreeMarker 没有给出失败的确切标记,但您可以从错误消息中找出答案。

        cfg.setTemplateExceptionHandler(new TemplateExceptionHandler() {
        @Override
        public void handleTemplateException(TemplateException te, Environment e, Writer writer) throws TemplateException {
            try {
                String errorString = te.getFTLInstructionStack();
                int startIndex = errorString.indexOf('$');

                if (startIndex != -1) {
                    int endIndex = errorString.indexOf('}', startIndex);
                    if (endIndex != -1) {
                        writer.write(errorString.substring(startIndex, endIndex + 1));
                    }
                    else {
                        throw te;
                    }
                }
                else {
                    throw te;
                }
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM