Difference between revisions of "Controlling whitespace in Jinja2 templates"

From Freephile Wiki
Jump to navigation Jump to search
(Created page with "right For background perspective, '''[https://jinja.palletsprojects.com Jinja]''' is used as a templating system by various Python projects li...")
(No difference)

Revision as of 13:47, 11 April 2024

Jinja-logo-sidebar.png

For background perspective, Jinja is used as a templating system by various Python projects like Django, Flask, or Ansible.

From the Jinja2 documentation, there are two options to control whitespace in Jinja templates:

  • trim_blocks
  • lstrip_blocks

But actually, there's more to it. The "Template Designer Documentation" specifically for whitespace control is inadequate. That's why I wrote this article.

Jinja in Ansible[edit | edit source]

In Ansible's Template module, you can see in the source code

But what does this mean? What do these options do? And how do I use them in my Ansible templates?

trim blocks means the first newline after a block is removed (block, not variable tag!)

lstrip blocks [1] means leading spaces and tabs are stripped from the start of a line to a block.

So, I can read words, but without context nor further example and explanation, I can't decode what "from the start of a line to a block" means.


In the task[edit | edit source]

In at least v2.9 of Ansible, the Template module has options to specify both.

In the template file[edit | edit source]

As the very first line of your template file, you can use a magic comment directive to control the behavior of the Ansible Template module #jinja2: trim_blocks: "true", lstrip_blocks: "true"[2]

By hand[edit | edit source]

If you're confused about Variable notation and how those are defined in templates, see https://jinja.palletsprojects.com/en/3.1.x/templates/#variables

Debugging[edit | edit source]

Just put {% debug %} somewhere in your template file.

References[edit source]

  1. lstrip stands for "left strip". It is a function in Python, as well as R and Ruby. Like ltrim in PHP or trimStart in JavaScript. nb. Jinja also has a built-in filter named trim that is used to strip characters from the beginning and end of a string.
  2. It's unclear whether the boolean value(s) to be quoted. I believe it was a bug that is now fixed - meaning they can be bare.