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

前端 未结 7 526
无人共我
无人共我 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 solved this for my very simple usecase (only using flat datastructure, no nesting (for example: ${parent.child}), lists or more specific) with dummy data provider:

    public class DummyDataProvider extends HashMap {
        private static final long serialVersionUID = 1;
    
        public final Set variables = new HashSet<>();
    
        @SuppressWarnings("unchecked")
        @Override
        public V get(Object key) {
            variables.add(key.toString());
            return (V) key;
        }
    }
    

    You can give this for processing to a template and when it finishes Set variables contains your variables.

    This is very simplistic approach, which certainly needs improvement, but you get the idea.

提交回复
热议问题