Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 在Jinja2中包装长文本节_Templates_Text_Jinja2_Long Integer_Multiline - Fatal编程技术网

Templates 在Jinja2中包装长文本节

Templates 在Jinja2中包装长文本节,templates,text,jinja2,long-integer,multiline,Templates,Text,Jinja2,Long Integer,Multiline,我有一个变量的定义,它的名称和一个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_usef

我有一个变量的定义,它的名称和一个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=value
    name=[value1,value2,value3]

当然,它不是傻瓜式的,但它满足了我的基本要求。

您可以在给定字符串前面加上换行符,然后使用
wordwrap
过滤器首先将文本包装成多行,然后使用
replace
过滤器将换行符替换为换行符加上
“#”:

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

以上假设您希望每行不超过80个字符。将
78
更改为所需的行宽减2,以便为
“#”留出空间。是的,谢谢,我会接受这个答案,因为它让我走上了正确的轨道,尽管我接着对它进行了一些修饰。我将用我提出的最终解决方案更新这个问题他被激怒了。