1

私は現在、フィールドをほとんど出力するテンプレートを作成しており、データベースからのコンテンツをプレーンテキストとしてダウンロードできるようにしています (ltsp の構成ファイルであると想定されています)。

私はよく次のようなことをします。

{% for model in modelqueryset %}
...
{% ifnotequal model.fieldx "" %}
    fieldx = {{ model.fieldx }}
{% endifnotequal %}
...
{% endfor %}

「...」は、次の長いリスト/多くのエントリ用です:

{% ifnotequal model.fieldy "" %}
    fieldy = {{ model.fieldy }}
{% endifnotequal %}

fieldx が実際に空の場合、空の行が表示されますが、それは不必要なスペースを占有し、平文を読みにくくします。質問に移りましょう:

これらの空行を削除するにはどうすればよいですか? {% spaceless %}...{% endspaceless %} を試しましたが、あまり役に立ちません。カスタムのテンプレートタグを書く必要がありますか、それとも何か間違ったことをしたり、何かを見落としたりしましたか?

どんな助けでも大歓迎です。私はすでに感謝しています

4

3 に答える 3

0

改行のため、空の行があります。

... <- here
{% ifnotequal model.fieldx "" %}
    fieldx = {{ model.fieldx }}
{% endifnotequal %}

こんな風に書き直せるので、

...{% ifnotequal model.fieldx "" %}
       fieldx = {{ model.fieldx }}
   {% endifnotequal %}

または、StripWhitespaceMiddlewareを試してください

于 2011-10-10T09:19:12.413 に答える
0

@DrTyrsa が言ったように、 StripWhitespaceMiddleware を使用できます。または、たまにしか空白を取り除きたくない場合は、このミドルウェアのコアを次のようなユーティリティ クラスに引き出すことができます。

import re
from django.template import loader, Context

class StripWhitespace():
    """
    Renders then strips whitespace from a file
    """

    def __init__(self):
        self.left_whitespace = re.compile('^\s+', re.MULTILINE)
        self.right_whitespace = re.compile('\s+$', re.MULTILINE)
        self.blank_line = re.compile('\n+', re.MULTILINE)


    def render_clean(self, text_file, context_dict):
        context = Context(context_dict)
        text_template = loader.get_template(text_file)
        text_content = text_template.render(context)
        text_content = self.left_whitespace.sub('', text_content)
        text_content = self.right_whitespace.sub('\n', text_content)
        text_content = self.blank_line.sub('\n', text_content)
        return text_content

次に、次のように views.py で使用できます。

def text_view(request):
    context = {}
    strip_whitespace = StripWhitespace()
    text_content = strip_whitespace.render_clean('sample.txt', context)
    return HttpResponse(text_content)

blank_lineすべての空白行を削除できるように、正規表現を追加したことに注意してください。セクション間に 1 行の空白行を表示したい場合は、この正規表現を削除できます。

于 2012-02-01T03:48:56.857 に答える
0

すべてにテンプレートを使用する必要はありません。単純な HttpResponse コンストラクターを使用して、Python で出力用のテキストを作成する方が簡単な場合があります。

>>> response = HttpResponse()
>>> response.write("<p>Here's the text of the Web page.</p>")
>>> response.write("<p>Here's another paragraph.</p>")
于 2011-10-10T11:54:58.327 に答える