简体   繁体   中英

How to call a Python function in Jinja template and use the returned dictionary from the functions values?

I have a function that reads from a file and returns a dictionary of d{1: 'a', 2: 'b', 3: 'c'}.

I want to send this function to a template and be able to call this function in my jinja template.

When I call this function in my Jinja template, I want to be able to use the returned dictionary values in the template. I plan to use AJAX to continually call this function in the template so that if the data in the file is changed ie 1: 'a' is changed to 1: 'f', the continuous function calls in the template will update the dictionary that is used in the template.

The function that retrieves the data from the file is called getdata() which returns the dictionary of the data.

I know you can use the .context_processor to make a function global and use the returned value in the template.

@app.context_processor
def utility_processor():
def format_price(amount, currency=u'$'):
  return u'{1}{0:.2f}'.format(amount, currency)
return dict(format_price=format_price)

and then you can call it in your template like so.

{{ format_price(0.33) }}

which outputs $0.33

Is it possible to achieve something like sending the function to the template and being able to call the context processer accessing a specific value in the returned dictionary within the template? Something like below.

@app.route('/')
def index():
return render_template('index.html')

@app.context_processor
def context_processor():
    return dict(datadict=getdata())

Access the first key in the dictionary like so.

{{ datadict.1 }}

which would output 'a'.

Is something like this possible?

Yes, look into python context objects . I recommend using a framework like django or flask to make it easier on yourself to deliver data from your server-side to the client. If you go down this route you will be able to bring the data to the client side simply by

@app.route('/')
def index():
data: {}
return render_template('index.html', data)

You can create your own filter :

from jinja2 import Environment

d = {1: 'a', 2: 'b', 3: 'c'}

env = Environment()
env.filters["myfilter"] = lambda k: d[k]

template = env.from_string("{{ val | myfilter }}")
print(template.render(val = 3))

prints

c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM