3

I have following code

String templateString = "Some Text $attribute1$ more text $attribute2$ more text"; 
ST stringTemplate = new ST(templateString ,'$','$');`

How can I iterate over all attributes i.e. attribute1, attribute2 etc? I want to get all list of attributes in template.

user3751014
  • 41
  • 1
  • 4

1 Answers1

0

In groovy was using just a regex like this and it seems to do what I need for now

   List<String> extractTemplateVariables( String statement ) {
    Pattern pattern = Pattern.compile( /\$(\w*)\$/ );
    def List<String> runTimeParms = []
    def matcher = pattern.matcher( statement )

    while (matcher.find()) {
        runTimeParms << matcher.group( 1 )

    }
    runTimeParms.removeAll( Collections.singleton( null ) );
    runTimeParms.unique( false )

}

But I've been told the proper way is to examine the ast something like this:

   final int ID = 25
    char delimiter = '$'
    ST st = new org.stringtemplate.v4.ST( statement, delimiter, delimiter );

    def dataFieldNames = []
    def t = st.getAttributes(  )
    st.impl.ast.getChildren().each {

        if (it != null) {
            CommonTree child = it as CommonTree
            if (child.toString().equals( "EXPR" )) {
                if (child.getChildCount() == 1) {
                    CommonTree expressionChild = child.getChild( 0 )
                    if (expressionChild.getToken().getType() == ID) {
                        dataFieldNames.add( expressionChild.toString() )
                    } else if (expressionChild.toString().equals( "PROP" )) {
                        if (expressionChild.getChildCount() == 2) {
                            dataFieldNames.add(
                                    expressionChild.getChild( 0 ).toString() +
                                            "." +
                                            expressionChild.getChild( 1 ).toString() )
                        }
                    }

                }
            }
        }
    }

    dataFieldNames.unique( false )

}

but I don't understand the structure or what I'm doing here, and it's not seeing any more than the first one. Maybe someone can help us figure out what the best way to do it would be

Jabrwoky
  • 61
  • 6