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

前端 未结 7 602
无人共我
无人共我 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

    one other way to get the variables from java. This just tries to process the template and catch the InvalidReferenceException to find all the variables in a freemarker-template

     /**
     * Find all the variables used in the Freemarker Template
     * @param templateName
     * @return
     */
    public Set getTemplateVariables(String templateName) {
        Template template = getTemplate(templateName);
        StringWriter stringWriter = new StringWriter();
        Map dataModel = new HashMap<>();
        boolean exceptionCaught;
    
        do {
            exceptionCaught = false;
            try {
                template.process(dataModel, stringWriter);
            } catch (InvalidReferenceException e) {
                exceptionCaught = true;
                dataModel.put(e.getBlamedExpressionString(), "");
            } catch (IOException | TemplateException e) {
                throw new IllegalStateException("Failed to Load Template: " + templateName, e);
            }
        } while (exceptionCaught);
    
        return dataModel.keySet();
    }
    
    private Template getTemplate(String templateName) {
        try {
            return configuration.getTemplate(templateName);
        } catch (IOException e) {
            throw new IllegalStateException("Failed to Load Template: " + templateName, e);
        }
    }
    

提交回复
热议问题