Jinja: 自动换行过滤器忽略现有的换行符

创建于 2013-02-05  ·  9评论  ·  资料来源: pallets/jinja

你好呀,

我注意到,当使用此过滤器(例如)确保电子邮件消息始终包装为 72 个字符(在可能的情况下)以确保尽可能频繁地显示时,我们注意到自动换行不会使用现有的换行符消息作为线索,但会严格每 72 个字符插入换行符。

这是我们的解决方法

## Workaround bug in do_wordwrap where it disregards existing linebreaks 
## when wrapping text

from jinja2.filters import environmentfilter
import re
<strong i="8">@environmentfilter</strong>
def do_wordwrap(environment, s, width=79, break_long_words=True):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`.
    """
    import textwrap
    accumulator = []
    # Workaround: pre-split the string
    for component in re.split(r"\r?\n", s):
        # textwrap will eat empty strings for breakfirst. Therefore we route them around it.
        if len(component) is 0:
            accumulator.append(component)
            continue
        accumulator.extend(
            textwrap.wrap(component, width=width, expand_tabs=False,
                replace_whitespace=False,
                break_long_words=break_long_words)
        )
    return environment.newline_sequence.join(accumulator)

不是很好和完整,但对我们有用。

我希望将这个(或类似的东西)包含在 jinja2 中,因为它使 wordrwap 过滤器更有用。

你怎么认为?

所有9条评论

我不认为这是一个错误。 Wordwrap 似乎只是假设您的文本尚未换行。

我不认为这是一个错误。 Wordwrap 似乎只是假设您的文本尚未换行。

嗯,很明显。 但是,在需要换行但要换行的文本已经包含某种形式的格式(例如分隔段落)的环境中,使用起来非常困难。

有这方面的消息吗? 我们有纯文本电子邮件,我们需要确保段落在末尾换行,但希望段落内的行自动换行。 这似乎是一个常见的用例。 事实上,我正在输入这条消息的这个评论框也是如此。 这些行会自动换行,但是当我按双输入时

一个新的段落开始。

您不能为此使用 stdlib 电子邮件模块吗?

你会在什么时候插入这个?
我们使用 Jinja2 来生成和本地化邮件,在编译模板后,将生成的字符串交给 pyramid_mailer/repoze_sendmail。

纯文本电子邮件模板如下所示:

{%- filter wordwrap(width=72, break_long_words=False) -%}
{% block greeting -%}
{% trans full_name = _(user.full_name) %}Hello {{ full_name }},{% endtrans %}
{% endblock -%}

{% block message_intro %}
{% endblock -%}

{% trans -%}
This may be a very long text in another language, depending on what a translator put into the gettext localization. It may even have its own paragraphs.
{%- endtrans %}

...

我也遇到了这个问题,谷歌搜索把我带到了这里。 使用@dwt的补丁对我

同样在这里,将修复程序合并到 master 中会很棒!

注意wrapstring在补丁中消失了

我提交了一个拉取请求,它在处理多个段落时解决了textwrap.wrap()这种有点意外的行为。

wrapstring和空行被保留。

我们正在使用此功能生成电子邮件正文作为另一个应用程序的一部分,并希望将输入包装在 80 列。

我在我的 nbconvert 模板中也遇到了这个问题。 合并 #766 会非常好,因为如果我必须编写自己的过滤器,我相信我必须为 nbconvert 编写一个自定义导出器,为了便于使用,我试图避免这样做。

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