微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何动态切换Jinja筛选器

如何解决如何动态切换Jinja筛选器

我目前正在制作一个显示用户交易列表的Web应用程序。我想进行设置以将货币从USD更改为EUR。我在Jinja中使用自定义过滤器:

我的自定义过滤器和功能

from forex_python.converter import CurrencyRates
from babel.numbers import format_currency

c = CurrencyRates()

# Format and convert transaction amount in EUR
def to_euros(value):
    value = c.convert('USD','EUR',value)
    return format_currency(value,locale='en_US')
app.jinja_env.filters['to_euros'] = to_euros

# Format transaction amount in USD
def to_usd(value):
    value = c.convert('USD','USD',locale='en_US')
app.jinja_env.filters['to_usd'] = to_usd

我的路线。py:

@app.route("/history",methods=['GET','POST'])
@login_required
def history():
    # Getting all transactions linked to user id
    row = Transactions.query.filter_by(user_id=current_user.id).order_by(Transactions.date.desc())
    return rnd_tmp("history.html",rows=row)

在我的html文件中:

{% extends "layout.html" %}

{% block title%}
    History
{% endblock %}

{% block main %}
    <div id="body-main">
        <table class="table table-striped table-full">
            <thead>
                <th>Date</th>
                <th>Type</th>
                <th>Category</th>
                <th>Amount</th>
                <th>Notes</th>
            </thead>
            <tbody>
                {% for row in rows %}
                    <tr>
                        <td>{{ row['date'] }}</td>
                        <td>{{ row['type'] }}</td>
                        <td>{{ row['category'] }}</td>
                        <td>{{ row['amount'] | to_usd }}</td>
                        <td>{{ row['notes'] }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
{% endblock %}

我想创建一条具有选择选项的新路线,以在美元和欧元货币之间进行更改,因此从<td>{{ row['amount'] | to_usd }}</td>更改为<td>{{ row['amount'] | to_euros }}</td>。 如何使用Flask动态地做到这一点?

解决方法

Jinja过滤器可以接受参数-请参见documentation。这意味着您可以编写一个更通用的to_currency过滤器,该过滤器可以将所选货币作为参数。

例如:

def to_currency(value,code):
    value = c.convert('USD',code,value)
    return format_currency(value,locale='en_US')

app.jinja_env.filters['to_currency'] = to_currency

您将在Jinja模板中以以下方式使用它:

<td>{{ row['amount'] | to_currency(selected_currency) }}</td>

字符串值selected_currency将从路由中以'USD''EUR'的形式传入。

请参见下图,其中显示了过滤器“值”的左侧与过滤器的参数一起传递到Python函数的位置:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。