我有一个变量的定义,它的名称和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 %}
要使用它,只需传递一个类似于顶部给出的规格的项目列表以及缩进和页面宽度。
一点解释:
name = value
或name = [ value1, value2, value3 ]
的形式呈现当然,它不是万无一失的,但它符合我的基本要求。
您可以使用换行符添加给定字符串,然后使用wordwrap
过滤器首先将文本换行为多行,并使用replace
过滤器将换行符替换为换行符加'# '
:
{{ ('\n' ~ item.comment) | wordwrap(78) | replace('\n', '\n# ') }}
以上假设您希望每行不超过80个字符。将78
更改为您想要的线宽减去2,为'# '
留出空间。