1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Jinja2のwhitespace controlについて

Last updated at Posted at 2018-02-13

Python(Jinja2)で出力したhtmlについて、インライン要素で謎の隙間が出てくる問題 が発生したので、Jinja2側で解決できないか調査。

アプリケーション側でできる設定

trim_blocks lstrip_blocks という設定を有効にすることで、ブロックのみの行(ifやfor文)は、スペースや改行を含めて何も出力しないようにできる。

ただし、これらは出力がないブロックのみの行にのみ適用されるもので、その行にhtml要素(タグor文字列)が埋め込まれていたり、ブロックから要素を出力した行には効かない。

foo.py
from jinja2 import Environment
jinja_env = Environment()
jinja_env.trim_blocks = True
jinja_env.lstrip_blocks = True

trim_blocks

ブロック({})の直後の改行を詰めて出力する

lstrip_blocks

ブロックの手前のスペースを詰めて出力する

html要素同士の改行スペースを詰める方法

htmlでコメントアウトする

   <span><!--
-->{{ hoge }}<!--
--></span>

cssで font-size:0; にする

<span style='font-size:0;'>
  {{ hoge }}
</span>

Jinja2のテンプレートで強制スペース詰めを行う

<span>
  {{- hoge -}}
</span>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?