How can I introspect a freemarker template to find out what variables it uses?

前端 未结 7 528
无人共我
无人共我 2021-01-01 15:27

I\'m not at all sure that this is even a solvable problem, but supposing that I have a freemarker template, I\'d like to be able to ask the template what variables it uses.<

相关标签:
7条回答
  • 2021-01-01 16:20

    I had the same problem and none of posted solution made sense to me. What I came with is plugging custom implementation of TemplateExceptionHandler. Example:

    final private List<String> missingReferences = Lists.newArrayList();
    final Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    cfg.setTemplateExceptionHandler(new TemplateExceptionHandler() {
    
        @Override
        public void handleTemplateException(TemplateException arg0, Environment arg1, Writer arg2) throws TemplateException {
            if (arg0 instanceof InvalidReferenceException) {
                missingReferences.add(arg0.getBlamedExpressionString());
                return;
            }
            throw arg0;
        }
    
    }
    
    Template template = loadTemplate(cfg, templateId, templateText);
    
    StringWriter out = new StringWriter();
    
    try {
        template.process(templateData, out);
    } catch (TemplateException | IOException e) {
            throw new RuntimeException("oops", e);
    }
    
    System.out.println("Missing references: " + missingReferences);
    

    Read more here: https://freemarker.apache.org/docs/pgui_config_errorhandling.html

    0 讨论(0)
提交回复
热议问题