【问题标题】:How to call a Python function in Jinja template and use the returned dictionary from the functions values?如何在 Jinja 模板中调用 Python 函数并使用函数值中返回的字典?
【发布时间】: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)

标签: python templates flask


【解决方案1】:

是的,请查看 python context objects。我建议使用 django 或 flask 之类的框架,以使您自己更轻松地将数据从服务器端传递到客户端。如果你沿着这条路线走,你将能够简单地将数据带到客户端

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

【讨论】:

    【解决方案2】:

    您可以创建自己的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))
    

    打印

    c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-04
      • 2011-08-31
      • 2021-09-20
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多