5

I'm creating script that generates specific files using jinja2 as template engine. It creates file I expect, except for the last line. In template I have specified last empty line, but when file is created it does not have that line.

Template looks like this:

# -*- coding: utf-8 -*-

from openerp import fields, models, api


class {{ class_name }}(models.{{ model_type }}):
    """{{ class_docstring }}"""

    _{{ def_type }} = '{{ model }}'
# Here is actually empty line. Note comment does not exist on template. It is just empty line.

So in total there are 10 lines defined in this template. But file that is created using this template will only have 9 lines (that last line will not be created).

Is this expected behavior or it should create me that last line as I am expecting?

Here data and methods that handle rendering:

from jinja2 import Environment, FileSystemLoader

PATH = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_ENVIRONMENT = Environment(
    autoescape=True,
    loader=FileSystemLoader(os.path.join(PATH, 'templates')),
    trim_blocks=False)
...
...
    @staticmethod
    def render_template(t, context):
        # For now it only supports standard templates.
        template_filename = TEMPLATE_FILES_MAPPING[t]
        return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(
            context)

2 Answers 2

5

The keep_trailing_newline option may be what you're looking for:

By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline.

You can add it to the environment:

TEMPLATE_ENVIRONMENT = Environment(
    ...
    keep_trailing_newline=True)
0

Another option is to finish the template with two newlines and let jinja2 strip one of them:

File contents
File contents
...
       # Actual empty line (without this comment) which is kept by jinja2
       # Actual empty line (without this comment) which is stripped by jinja2
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Nov 28, 2022 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.