Django 模板标签创建空间

问题描述 投票:0回答:2

我正在开发一个 Django 网站,该网站位于 this site。 由于 HTML 中不需要的空格,我的输出中出现了不需要的空格。

例如,“01-1737 , Civilian Review Authority , INAPPLICATE LANGUAGE, SUSTAINED”在大多数逗号之前都有额外的空格。

我发现其他帖子也有类似问题,但没有解决方案对我有用。我尝试了 {% spaceless %} 标签,但这不起作用。 唯一对我有用的就是将 for 循环中的所有模板标签放在一行上,但我真的很想找到比这更可读的解决方案。

这是 Django 模板的代码:

{% extends 'police_archive/base.html' %}

{% block content %}
    <h2> {{officer.first_name}} {{officer.last_name}}, badge #{{officer.badge}} </h2>
    <p><strong>Department:</strong> {{officer.department}}</p>
    <h2>Complaints</h2>
    <ul>
        {% for details in details_list %}
            <li>


                {% if details.incident.case_number %}
                    <a href='/police_archive/complaint/{{details.incident.case_number}}'>
                         {{details.incident.case_number}}
                    </a>
                {% else %}
                 No Case Number Found
                {% endif %}


                {% if details.incident.office %}
                 , {{details.incident.get_office_display}}
                {% else %}
                , No office found
                {% endif %}

                {% if details.allegation %}
                 , {{details.allegation}}
                {% endif %}

                {% if details.finding %}
                 , {{details.finding}}
                {% endif %}

                {% if details.action %}
                 , {{details.action}}
                {% endif %}  

            </li>
        {% endfor %}


{% endblock %}
python django
2个回答
1
投票

{% spaceless %}
没有为您删除所有空间的原因是因为它仅适用于HTML标签。您的空白出现在 <li> 标签中
内。

我似乎无法为 Django 的标准模板系统找到一个好的解决方案,但它看起来确实

Jinja 提供了您正在寻找的东西。它使用破折号来去除尾随或前导空格:

{% for item in seq -%} {{ item }} {%- endfor %}

为了使用 Jinja 而不是 Django 的默认模板系统,您必须按照

Django 文档

中所述更改您的 
settings.py 文件:

TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2.', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { # ... some options here ... }, }, ]
    

0
投票
已经过去七年了,但是对于那些带着同样问题来到这里的人来说,下面的帖子对我有所帮助。

https://www.reddit.com/r/django/comments/1bykhnl/remove_white_space/

我基本上跨越了每根弦并使用了无空格

我的最终看起来像这样↓

{% spaceless %} <p> by {% for author in article.author.all %} {% if forloop.last and not forloop.first%} <span> and </span> {% elif not forloop.first %} <span>, </span> {% endif%} <a href="#">{{author}}</a> {% empty %} <p>Unknown</p> {% endfor %} </p> {% endspaceless%}
→ 作者 1、作者 2、作者 3 和作者 4 

希望对您有用;)

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