FortiSOAR Discussions
srivastavad
Staff
Staff

FortiSOAR Recommends Best Practices for Seamless Integration of Jinja and Python in Code

In the context of utilizing Jinja and Python, say, an error has surfaced while executing a playbook. Although there's an initial assumption that FortiSOAR might be struggling to parse elements, it's worth considering that this may not be the actual cause. Here's why.


The challenge often arises when attempting to mix Jinja, a templating engine commonly used in web frameworks like Flask, with Python code. Here, is a list of best practices to overcome the problem:

 

Best Practices:

  1. Optimizing Jinja Usage:

    • Keep Jinja expressions focused on providing inputs and avoid mixing them with Python logic.
    • Use Jinja primarily for templating and rendering dynamic content.
  2. Awareness of Evaluation Order:

    • Understand that Jinja expressions are evaluated before Python code.
    • Be cautious when using Jinja within comments or multiline strings in Python code.
  3. Clean Code:

    • Remove unnecessary or unused Jinja expressions from the code.
    • Clearly document the purpose of Jinja expressions to enhance code readability.

Now, let's apply these best practices to a sample code snippet where Jinja expressions are causing issues.

In this snippet, the focus is on providing inputs using Jinja, and unnecessary expressions have been removed. Additionally, unused variables and Jinja expressions within comments have been eliminated to prevent evaluation issues.

Code snippet with issues:

for ticket in output_list:
open_timestamp = "{{arrow.get(ticket['opened_at'],'YYYY-MM-DD HH:mm:ss').shift(hours=+8).format('MM/DD/YYYY, hh:mm:ss A')}}"
work_notes += f'{ticket["number"]} - {ticket["short_description"]} - Opened:'


Here, is the revised code, based on the best practices:

open_timestamp = "{{arrow.get(ticket['opened_at'],'YYYY-MM-DD HH:mm:ss').shift(hours=+8).format('MM/DD/YYYY, hh:mm:ss A')}}"

#more_notes = '\n'.join(f'{ticket['number']} - {ticket['short_description']} 

1 REPLY 1
malayamanas_FTNT

We can comment to JINJA code like below.

{# open_timestamp is STRING variable defined in a SET VARIABLE STEP and its value generated by arrow filter. For more information refer https://arrow.readthedocs.io/en/latest/ . #}

open_timestamp = "{{arrow.get(ticket['opened_at'],'YYYY-MM-DD HH:mm:ss').shift(hours=+8).format('MM/DD/YYYY, hh:mm:ss A')}}"

 

Here, whatever we write inside {# #} , goes as a comment to understand the throughts behind JINJA code.

MALAYA MANAS PANDA
Professional Services Consultant