Python Flask jinja2 在模板中使用数学模块 sin() cos()

标签 python flask jinja2

我目前正在实现半径过滤系统。

用户可以搜索某个城市的房间,根据搜索到的城市的经纬度,结果页面将显示60公里半径范围内的所有其他房间。

我找到了一个工作函数,我已经测试过它(尽管数字太高,相对比例仍然显示正确的结果):

acos(sin(loc_latitude) * sin(zimmer.zimmer_lat) + cos(loc_latitude) * cos(zimmer.zimmer_lat) * cos(zimmer.zimmer_lng - (loc_longitude))) * 6371 <= 6000:

我需要这个作为 jinja if 表达式:

{% if acos(sin(loc_latitude) * sin(zimmer.zimmer_lat) + cos(loc_latitude) * cos(zimmer.zimmer_lat) * cos(zimmer.zimmer_lng - (loc_longitude))) * 6371 <= 6000 %}

但是在模板中 jinja 不知道我从数学模块导入的 cos() 和 sin() 函数:

 File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\templates\zimmer_gefunden.html", line 149, in block "content"
{% if acos(sin(loc_latitude) * sin(zimmer.zimmer_lat) + cos(loc_latitude) * cos(zimmer.zimmer_lat) * cos(zimmer.zimmer_lng - (loc_longitude))) * 6371 <= 60 %} 
UndefinedError: 'sin' is undefined

有没有办法将这些函数传递给模板?

我看到了这个:

your_template.render(sin())
your_template.render(cos())

但我不明白从哪里获取 your_template,因为我已经像这样渲染模板:

return render_template('zimmer_gefunden.html', mymap=mymap, paginator_find=paginator_find, findroomcity=findroomcity, 
                    form=form, pagenumber_find=pagenumber_find, all_rooms_in_city=all_rooms_in_city, pages_list_find=pages_list_find, all_einzelzimmer = all_einzelzimmer,
                    all_doppelzimmer = all_doppelzimmer, all_mehrbettzimmer = all_mehrbettzimmer, all_wohnung = all_wohnung,
                    loc_latitude = loc_latitude, loc_longitude = loc_longitude)

或者还有其他方法吗?

最佳答案

来自Flask docs :

To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app

基本上,只需将其添加到您的代码中,您就可以在所有模板中使用这些函数。

from math import sin, cos, acos

@app.context_processor
def utility_processor():
    return dict(cos=cos, sin=sin, acos=acos)

将任何其他函数或变量添加到返回的 dict 中,以使它们可用于您的模板。

关于Python Flask jinja2 在模板中使用数学模块 sin() cos(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848688/

相关文章:

python - OpenCV imwrite 不保存照片,返回 false

python - RobotFramework - 从 python 库调用函数

Python:Flask 缓存一段时间

python - Flask session 不持久

python - AIOHTTP Server - 用于引发条件的 Jinja 模板

python - Jinja2 仅加入列表

python - Google Pubsub Python 客户端库订阅者随机崩溃

python - 将 Canvas 图像中的图像保存到 Django 文件夹中

python - 为多个 celery worker 和线程正确设置 Flask-SQLAlchemy

python - Jinja2 将 float 转换为小数中间计算