2

For example, if I have a template such as

"SELECT * FROM myOrders WHERE order_id = ${orderId} and order_date = ${orderDate}"

I would like to get a list of all placeholders in that template, i.e. ['orderId', 'orderDate']

Padraic Cunningham
  • 160,756
  • 20
  • 201
  • 286
victtim
  • 620
  • 4
  • 15

3 Answers3

1

I can use a regex to pull those placeholders out.

p.s. Still, it would be nice to have that feature in the Cheetah API, perhaps in the Template class.

example:

import re
templateDef = """
SELECT * FROM myOrders WHERE order_id = ${orderId} and order_date = ${orderDate}
"""
placeholders = re.findall(r"\${(\w+)}", templateDef)
print placeholders
victtim
  • 620
  • 4
  • 15
1

Formatter.parse should work:

s = "SELECT * FROM myOrders WHERE order_id = ${orderId} and order_date = ${orderDate}"

from string import Formatter
#literal_text, field_name, format_spec, conversion
print([plh for _, plh, _,_  in Formatter().parse(s) if plh])
['orderId', 'orderDate']
Padraic Cunningham
  • 160,756
  • 20
  • 201
  • 286
0

This code:

vars = set()

class DummyDict:
    def __getitem__(self, key):
        vars.add(key)
        return 'X'

str(Template('Hello $A $B $C', searchList=[DummyDict()]))

print(vars)

Prints:

{'B', 'A', 'C'}

andrch
  • 171
  • 1
  • 2