pystache
pystache copied to clipboard
Add a get_keys() method to ParsedTemplate class
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()