0

我有一个函数,当被调用时,它会遍历一个包含注释的字典对象,然后应该显示每一个用一行分隔的。

我已经搜索了有关此的其他主题,但没有找到任何可以回答我的主题。

我试过'\n''',但总是把文字放在一起。

def get_comment(stand):
    ''' Takes a comment code from the each of the comments
    field from inside the stand data and outputs
    a human readable text comment '''
    for _i in range(8):
        if stand:
            for _ in range(len(stand)):
                comments = []
                for _key, codes in stand.items():
                    comment = codes['carrier'] + ':' + \
                    codes['number'] + ' - ' + \
                    SamCode.objects.get(code=codes['dockingCode']).comment
                    comments.append(comment)

            return '\n'.join(comments)

这输出

例如。

AA:2776 - Manual start of system - ground AA:335 - Manual start of system - ground

而我需要成为

AA:2776 - Manual start of system - ground

AA:335 - Manual start of system - ground

为 Django 集成添加 html 模板代码。Column.13 和 Column.14 一样可以有一个或多个评论。取决于评论的来源。

   {% for column in performance.dailyDetails %}
    <td>{{ column.0 }}</td>
    <td>{{ column.1 }}</td>
    <td>{{ column.2 }}</td>
    <td>{{ column.3 }}</td>
    <td>{{ column.4 }}</td>
    <td>{{ column.5 }}</td>
    <td>{{ column.6 }}</td>
    <td>{{ column.7 }}</td>
    <td>{{ column.8 }}</td>
    <td>{{ column.9 }}</td>
    <td>{{ column.10 }}</td>
    <td>{{ column.11 }}</td>
    <td>{{ column.12 }}</td>
    <td>{% if column.13 == None %}
        {% else %}
          {{ column.13 }}<br>
        {% endif %}
        {% if column.14 == None %}
        {% else %}
          {{ column.14 }}<br>
        {% endif %}</td>

这是正在循环的 JSON 字典之一。IT 已经在注释中显示了 \n,但在输出到 HTML 时它不是换行符:

{'partition': 'AA',
 'date': '04/14/2019',
 'sortingName': 'ORD.H16', 
 'stand': 'ORD.H16', 
 'acType': 'A321,A321/2,B737/8-WL', 
 'inbound': 7, 
 'outbound': 2, 
 'blockIn': 4, 
 'blockOff': 2, 
 'slaInbound': 4, 
 'slaOutbound': 2, 
 'samInternal': None, 
 'sdkTechnical': None, 
 'ground': 'AA:2776 - Manual start of system - ground\nAA:335 - Manual start of system - ground', 
 'pilot': 'AA:362 - UNK - pilot', 
 'tower': None, 
 'operational': None, 
 'infrastructure': None, 
 'interface': None}
4

2 回答 2

2

这完全是输出的问题。HTML 忽略空格,包括换行符;如果您希望数据出现在多行中,您需要使用 HTML 换行元素,例如<br>.

有一个 Django 模板过滤器,可以将换行符转换为 HTML 中断:linebreaksbr.

{{ column.13|linebreaksbr }}
于 2019-04-15T14:12:37.473 回答
0

确保注释列表中的所有元素都是字符串对象。

关于您关于在评论之间添加换行符的问题,您几乎是正确的。如果你打印函数的返回值,你会得到正确的输出

前任:

>>> x= '\n'.join(['1','2','3'])
>>> x
'1\n2\n3'
>>> print (x)
1
2
3
于 2019-04-15T13:54:47.983 回答