在Jinja2中包装长文本部分

问题描述 投票:1回答:1

我有一个变量的定义,它的名称和YAML文件中的相关注释,我正在尝试使用Jinja2创建一个合适的目标文件;在这种情况下是专有的配置文件

...
- comment: >
      This is a comment which will almost certainly end up longer than standard eighty characters or at least on the occasion on which it does. 
  name: my_useful_variable
  value: /a/long/example/path/to/my/file.txt

我希望这个文本呈现如下:

# This is a comment which will almost certainly end up
# longer than standard eighty characters or at least on
# the occasion on which it does.
my_useful_variable = "/a/long/example/path/to/my/file.txt"

Jinja2是否有任何方式来包装文本,以便长注释行的长度有限并且需要分割多少行?

到目前为止,我有:

# {{item.comment}}    
{{item.name}} = "{{item.value}}"

但这当然不涉及评论的长度。

继下面的@blhsing提供的答案之后,我提出了以下宏,它适用于基本变量和简单列表(即不是字典或更复杂的分层数据结构:

{% macro set_params(param_list, ind=4, wid=80) -%}
{% for item in param_list %}
{% if item.comment is defined %}{{item.comment|wordwrap(wid - ind - 2)|replace('',  ' ' * ind +'# ', 1)|replace('\n', '\n' + ' ' * ind + '# ')}}
{% endif %}
{% if item.value is iterable and item.value is not string %}{{item.name|indent(ind, True)}} = [ {% for item_2 in item.value %}{{item_2}}{{ ", " if not loop.last else " " }}{% endfor %}{% else %}{{item.name|indent(ind, True)}} = {{item.value}}{% endif %}
{% endfor %}
{%- endmacro %}

要使用它,只需传递一个类似于顶部给出的规格的项目列表以及缩进和页面宽度。

一点解释:

  • 第3行,如果定义了注释,那么它会被包装到正确的长度,并记住宽度和缩进。第一个替换处理缩进第一行,第二个缩进后续行。全部以“#”为前缀
  • 第5行,取决于变量是简单的还是可迭代的,它以name = valuename = [ value1, value2, value3 ]的形式呈现

当然,它不是万无一失的,但它符合我的基本要求。

templates text jinja2 long-integer multiline
1个回答
1
投票

您可以使用换行符添加给定字符串,然后使用wordwrap过滤器首先将文本换行为多行,并使用replace过滤器将换行符替换为换行符加'# '

{{ ('\n' ~ item.comment) | wordwrap(78) | replace('\n', '\n# ') }}

以上假设您希望每行不超过80个字符。将78更改为您想要的线宽减去2,为'# '留出空间。

© www.soinside.com 2019 - 2024. All rights reserved.