Jinja: urlencode 过滤器丢失?

创建于 2011-03-08  ·  6评论  ·  资料来源: pallets/jinja

你好,

在内置过滤器列表(http://jinja.pocoo.org/docs/templates/#list-of-builtin-filters)中我没有找到“urlencode”过滤器。 是失踪了吗?

我不明白,在 jinja1 中存在这个过滤器: http ://wsgiarea.pocoo.org/jinja/docs/filters.html

你对此有何评论?

问候,
斯蒂芬妮

最有用的评论

对于任何偶然发现此过滤器并寻找urlencode过滤器的人,它于 2012 年在 06a8b1c02b2091b31ef4f39ddde3184f25f58260 和 5145401fe5f9995a32757f34359623b87048ab8b 中添加。 #85 中的讨论。

它被称为urlencode而不是urlquoteurlquoteplusurlquote_plusurlescape (为其他通过搜索登陆的人添加这些)。

所有6条评论

为什么不自己做呢? 在制作时,请注意了解 urllib.urlencode、urllib.quote 和 urllib.quote_plus 之间的关系。

对我来说,我最终制作了一个可以用作过滤器和可调用函数的函数(为烧瓶应用程序完成):

@app.template_filter('urlencode')
def urlencode(uri, **query):
   parts = list(urlparse.urlparse(uri))
   q = urlparse.parse_qs(parts[4])
   q.update(query)
   parts[4] = urllib.urlencode(q)
   return urlparse.urlunparse(parts)
app.jinja_env.globals['urlencode'] = urlencode

在模板中作为函数使用:

{% set vendor_url = urlencode('http://www.google.com/search', q=adset.keyword.text) %}

在模板中用作过滤器:

{% set vendor_url = 'http://www.google.com/search?q=%s' % querytext %}
{{ vendor_url|urlencode }}

为什么不自己做呢?

因为 jinja2 已经有很多内置过滤器(http://jinja.pocoo.org/docs/templates/#builtin-filters),而 urlencode 是一个经典功能,可以附加到内置过滤器中。

问候,
斯蒂芬妮

urllib.quote_plus(uri)

如果这可以提交到主版本,那就太好了。 在 jinja2 这样完整的模板系统中,这是人们所期望的。

@radekstepan @gfuchedzhy我的印象是它不像通过引号或引号加上传递字符串/标记那么简单。 就我而言,这导致了quote_plus 中的unicode 问题。 似乎必须将 unicode 编码为 utf-8 才能与 quote_plus() 很好地配合使用。 这是我的解决方案:

@app.template_filter('urlencode')
def urlencode_filter(s):
    if type(s) == 'Markup':
        s = s.unescape()
    s = s.encode('utf8')
    s = urllib.quote_plus(s)
    return Markup(s)

对于任何偶然发现此过滤器并寻找urlencode过滤器的人,它于 2012 年在 06a8b1c02b2091b31ef4f39ddde3184f25f58260 和 5145401fe5f9995a32757f34359623b87048ab8b 中添加。 #85 中的讨论。

它被称为urlencode而不是urlquoteurlquoteplusurlquote_plusurlescape (为其他通过搜索登陆的人添加这些)。

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

mitsuhiko picture mitsuhiko  ·  3评论

dwt picture dwt  ·  3评论

hvnsweeting picture hvnsweeting  ·  4评论

priestc picture priestc  ·  5评论

AMDmi3 picture AMDmi3  ·  4评论