简体   繁体   English

如何在Jinja模板中调用Python函数并使用函数值返回的字典?

[英]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'}. 我有一个从文件读取并返回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. 我想将此函数发送到模板,并能够在我的jinja模板中调用此函数。

When I call this function in my Jinja template, I want to be able to use the returned dictionary values in the template. 当我在Jinja模板中调用此函数时,我希望能够在模板中使用返回的字典值。 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. 我计划使用AJAX在模板中连续调用此函数,以便如果更改文件中的数据,即1:“ a”更改为1:“ f”,则模板中的连续函数调用将更新字典,在模板中使用。

The function that retrieves the data from the file is called getdata() which returns the dictionary of the data. 从文件中检索数据的函数称为getdata(),该函数返回数据的字典。

I know you can use the .context_processor to make a function global and use the returned value in the template. 我知道您可以使用.context_processor来使函数成为全局函数,并在模板中使用返回的值。

@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 输出$ 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'. 这将输出“ a”。

Is something like this possible? 这样的事情可能吗?

Yes, look into python context objects . 是的,研究python 上下文对象 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. 我建议使用django或flask之类的框架,以使自己更轻松地将数据从服务器端传递到客户端。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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