Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a get_keys() method to ParsedTemplate class #173

Open
martin-langhoff opened this issue May 21, 2015 · 0 comments
Open

Add a get_keys() method to ParsedTemplate class #173

martin-langhoff opened this issue May 21, 2015 · 0 comments

Comments

@martin-langhoff
Copy link

For some use cases, the application using templates needs to know which keys the template is using.

For example:

  • where the "natural" key names are long/unwieldy, and the user can input an easier key ("name") and then provide a mapping in a complementary UI (matching 'name' to 'foo.bar.baz.TheFrobName', picked from a dropdown).
  • where resolving a key is expensive, and the scope carries many keys possible keys

So we end up using a utility function like:

def pystache_template_parsekeys(template):
    # fragile, relies on pystache internals
    parsed_template = pystache.parse(template)
    keys = []
    parse_tree = parsed_template._parse_tree
    keyed_classes = ( pystache.parser._EscapeNode,
                      pystache.parser._LiteralNode,
                      pystache.parser._InvertedNode,
                      pystache.parser._SectionNode )
    for token in parse_tree:
        if isinstance(token, keyed_classes):
            keys.append(token.key)
    # return list of unique items
    # (json does not like sets)
    return list(set(keys))

Obviously this will break if/when Pystache internals move around.

It would be much saner if Pystache had this internally, then we could do

 parsed_template = pystache.parse(template)
 keys = parsed_template.keys()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant