【发布时间】:2019-04-23 16:34:14
【问题描述】:
我有一个从文件中读取并返回 d{1: 'a', 2: 'b', 3: 'c'} 的字典的函数。
我想将此函数发送到一个模板,并能够在我的 jinja 模板中调用此函数。
当我在我的 Jinja 模板中调用这个函数时,我希望能够在模板中使用返回的字典值。我计划使用 AJAX 在模板中不断调用此函数,以便如果文件中的数据发生更改,即 1:'a' 更改为 1:'f',模板中的连续函数调用将更新字典在模板中使用。
从文件中检索数据的函数称为 getdata(),它返回数据的字典。
我知道您可以使用 .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)
然后你可以像这样在你的模板中调用它。
{{ format_price(0.33) }}
输出 $0.33
是否有可能实现诸如将函数发送到模板并能够调用上下文处理器访问模板内返回的字典中的特定值之类的东西?如下所示。
@app.route('/')
def index():
return render_template('index.html')
@app.context_processor
def context_processor():
return dict(datadict=getdata())
像这样访问字典中的第一个键。
{{ datadict.1 }}
会输出'a'。
这样的事情可能吗?
【问题讨论】:
-
你的函数将输出
0.33$,而不是$0.33 -
可以不用自带函数格式化:stackoverflow.com/questions/12681036/…
-
啊,是的,你说得对。在那里修好了。
-
对我来说你应该在
index()获取数据,处理数据并发送到模板render_template('index.html', data)