Home > Blockchain >  Getting list of context variables out of string
Getting list of context variables out of string

Time:09-28

I have the following string in my Django app: "Hello, {{ name }}. I will arrive at {{ time }}". My goal is to come up with a list of variables that is used in that string:

def my_func():
   # What should be done here ?

my_str = "Hello, {{ name }}. I will arrive at {{ time }}"
print(my_func(my_str))  # Desired output ["name", "time"]

The desired output here should be ["name", "time"]. Currently, I am going to implement that invoking a regexp, but I feel like there must be some in-built way to achieve that. Any hints ?

CodePudding user response:

You can use jinja2schema.infer to get the list of variables used in template:

import jinja2schema

def my_func(my_str):
   return list(jinja2schema.infer(my_str).keys())

my_str = "Hello, {{ name }}. I will arrive at {{ time }}"
variables = my_func(my_str)

variables should look like:

['time', 'name']
  • Related