pallets / jinja

A very fast and expressive template engine.
https://jinja.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
10.12k stars 1.6k forks source link

Jinja strips trailing newline #1961

Closed mgoral closed 3 months ago

mgoral commented 3 months ago

Hello,

I'm aware of issue #848 and keep_trailing_newline option. I believe that keep_trailing_newline=True should be a default option and having it set to False by default is a bug which breaks the principle of least astonishment. My reasoning follows.

  1. Jinja should not modify by itself templates which user provides. Jinja should follow explicitly what user asks Jinja to do. Stripping any characters from the template without user's consent is incorrect behavior of templating engine. If user provides a string without a newline character, Jinja should output the string without a newline character. If user provides a string with a newline character, Jinja should output a string with a newline character.
  2. Current behavior is inconsistent with the trim_blocks, which is set to False by default, and with how trimming requires a dash character in templates ({%- -%}). How come that users must explicitly tell Jinja to trim one kind of whitespaces, but not the other?
  3. The popular use case for Jinja is to read templates from the file and output them back to another file. Text files are made of lines, which POSIX specifies as a sequence of characters plus newline character. By stripping the newline character, programs which use default Jinja will produce files with invalid lines, which may lead to subtle errors: a use case visible for unaware users of cat utility and the author of #848.
  4. I'm a proponent of "deep" modules with simple interfaces, which address a common use case (as described by John Ousterhout in "The Philosophy of Software Design, 2nd Edition"). I believe a common use case here is to not change the passed templates. Currently Environment class has 22 initialization parameters. Users shouldn't need to go through the whole list each time they create environment just to achieve a common use case. Only special corner cases should require modification of these parameters.