Django - 从自定义过滤器中访问 RequestContext [英] Django - accessing the RequestContext from within a custom filter

查看:27
本文介绍了Django - 从自定义过滤器中访问 RequestContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个过滤器currency,它以美元为单位取值并将其转换为货币(美元或英镑).要转换的货币存储在会话中,但过滤器不接受 RequestContext,所以我不能直接从那里获取它.

I've got a filter currency, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take RequestContext, so I can't grab it straight from there.

有没有比将相关会话元素传递到模板中,并从模​​板中作为参数传递到过滤器中更好的方法?虽然这种方法有效,但它看起来相当糟糕,而且我很可能最终将货币传递给(几乎)每个模板.

Is there a better way than passing the relevant session element into the template, and from the template into the filter as an argument? Whilst this approach is working, it seems fairly horrible, and I'm likely to end up passing the currency to (almost) every template.

我的过滤器目前看起来像这样:

My filter currently looks something like this:

def currency(value, currency):
    if currency == 'usd':
       val = '$%.2f' % value
       return mark_safe(val)

    d = Decimal(value)
    val = '£%.2f' % (d*Decimal('0.63'))

    return mark_safe(val)

推荐答案

如果您创建模板标记而不是过滤器,则会为您提供要使用的上下文(其中包含请求).http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

If you create a template tag instead of a filter, you are given the context to work with (which contains the request). http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

这篇关于Django - 从自定义过滤器中访问 RequestContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆