Skip to content

Instantly share code, notes, and snippets.

@lamehost
Last active January 20, 2023 15:28
Show Gist options
  • Save lamehost/89550962f91637d165b3bd50c28140c0 to your computer and use it in GitHub Desktop.
Save lamehost/89550962f91637d165b3bd50c28140c0 to your computer and use it in GitHub Desktop.
Jinja2 whitespaces

Jinja2 whitespaces

Dealing with Jinja2 whitespaces it’s a nightmare.
Here’s my trick to get rid of that pain.

Let’s say that you have an array like this:

[
 {
  "address": "192.0.2.1", 
  "local_as": 64497, 
  "remote_as": 64498
 },
 {
  "address": "192.0.2.2", 
  "remote_as": 64499
 }
]

And you want to transform it as something like

!
router bgp 64496
 neighbor 192.0.2.1
  local-as 64497
  remote-as 64498
 !
 neighbor 192.0.2.2
  remote-as 64499
 !
!

Since local_as is not always present you’ll have to deal with an if condition within your template, and that is one of those things that get indentation messy.

For instance you should end up with:

!
router bgp 64496
 neighbor 192.0.2.1
   local-as 64497
  remote-as 64498
 !
 neighbor 192.0.2.2
  remote-as 64499
 !
!

Here’s what you can do. Instead of relying on Jinja2’s indentation you completely ignore it and write your code as usual python (note that i am using hashtags instead of bracket percent)

!router bgp 64496
 # for neighbor in neighbors
  ! neighbor {{neighbor['address']}}
  # if 'local_as' in neighbors
   !  local-as {{neighbor['local_as']}}
  # endif
  !  remote-as {{neighbor['remote_as']}}
  ! !
 # endfor
!!

When you render it the result looks like:

!router bgp 64496
  ! neighbor 192.0.2.1
  !  remote-as {{neighbor['remote_as']}}
   !  local-as 64497
  ! !
  ! neighbor {{neighbor['address']}}
  !  remote-as {{neighbor['remote_as']}}
  ! !
!!

Now all that you have to do is to lstrip() all the lines and ditch the leftmost character:

txt = template.render(neighbors=neighbors)
txt = '\n'.join([_.lstrip()[1:] for _ in txt.splitlines()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment