Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

java - StringTemplate list of attributes defined for a given template

I am getting started with StringTemplate 4 and I am trying to create a template from a simple string stored in a database. I use something like this:

STGroup group = new STGroupString(null, someTemplateString, '$', '$');
ST st = group.getInstanceOf(someTemplateName);
st.add(someAttribute, someValue);

Now everything works fine if I define all or less than the attribute defined for the template someTemplateName. Now if I try to add an attribute that doesn't exist, I get the following exception:

no such attribute: fake
java.lang.IllegalArgumentException: no such attribute: fake
  ...

which makes sense. However, it seems like there's no way for me to know beforehand which attributes are defined for the template someTemplateName. I was expecting to find something like:

bool isDef = st.isDefined(someAttribute);

but there's no such method. Am I correct? Is there any way around this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The documentation for CompiledST states tokens is only for debug. Not sure what that means.

ST template = new ST("Hello <username>, how are you? Using <if(condition)>expression<endif> in condition works, and repeating <username> is not a problem.");
Set<String> expressions = new HashSet<String>();
TokenStream tokens = template.impl.tokens;
for (int i = 0; i < tokens.range(); i++) {
    Token token = tokens.get(i);
    if (token.getType() == STLexer.ID) {
        expressions.add(token.getText());
    }
}

Gives you the Strings username and condition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...