velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Vos, Jerry R." <jerry....@gmail.com>
Subject List of variables from template
Date Tue, 03 May 2005 21:52:15 GMT
Hello all,
I'm looking for a way to get a list of the variables referenced in a 
template.  I found a message titled "List of variables present in template?"
http://mail-archives.apache.org/mod_mbox/jakarta-velocity-user/200111.mbox/%3CNEBBKJJKKLLIEBBNBNHHMEMECLAA.ewan_makepeace@yahoo.com%3E
with a comment from "Geir Magnusson Jr." (I believe, hard to follow the 
 >>'s) saying he was going to work on implementing this, but I can't 
find more information on if this was done.

As of right now I've coded a somewhat hackish way of doing it by taking 
the contents of Velocity.evaluate(...), but I was wondering if there's 
an implementation out there (so I have less to test). 

I'm only working with small strings that are getting filled in, along 
the lines of "$Var1 ya da ya da $Var2 fadfas ${Var_3}" so it doesn't 
have to be overly robust.  And yes, I know to some extent velocity is 
overkill for this use, but it simplifies my life.

In case anyone's curious, here's the current code I have:

    public static ArrayList<String> templateVarNames(VelocityContext 
context,
            String toParse) {
        SimpleNode nodeTree = null;
        ArrayList<String> varNames = new ArrayList<String>();

        try {
            nodeTree = RuntimeSingleton.parse(new BufferedReader(
                    new StringReader(toParse)), toParse);
        } catch (ParseException pex) {
            // TODO: do something with this error
            return null;
        }

        if (nodeTree != null) {
            InternalContextAdapterImpl ica = new InternalContextAdapterImpl(
                    context);

            ica.pushCurrentTemplateName(toParse);

            try {
                nodeTree.init(ica, RuntimeSingleton.getRuntimeServices());

                // Find the templates and extract their names
                for (int i = 0; i < nodeTree.jjtGetNumChildren(); i++) {
                    Node node = nodeTree.jjtGetChild(i);

                    if (node instanceof ASTReference) {
                        varNames.add(((ASTReference) node).getRootString());
                    }
                }
            } catch (Exception e) {
            // TODO: do something with this error

                return null;
            }
        }

        return varNames;
    }



Jerry Vos

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Mime
View raw message