Jinja Syntax

This section covers the basics of Jinja syntax that are most relevant for exporting reports from PlexTrac to Word.

Syntax

Syntax is the set of rules that defines the combinations of symbols that are considered to be correctly structured statements or expressions. Jinja2 (known as ‘Jinja’ moving forward) is derived from Python and much of its code is directly or very close to Python, including much of the syntax.

When writing Jinja, there are two types of statements: Print and Logic

A print statement tells the code to write out something specified. In Python this would look something like:

print(“Hello World”)

In Jinja, this looks a little different; the ‘print’ part of the statement is replaced with {{ and }}. Anything between that should print out in the Word Document.

This is the basic structure of a print statement: {{ VARIABLE or CODE }}

Here is a real example:

{{REPORT_INFO.prepare_for}}

This grabs data from PlexTrac and prints it out in the Word Document. When you get your Exported Word Document, that line will be replaced with the data that was pulled from PlexTrac and becomes something like:

COMPANY NAME

Logic Statement

A logic statement is where the heavy lifting of programming is done. With Logic Statements, you can create conditionals, check variables, define a scope, and so much more. In other languages, this is the same type of statement your using when you define a function, variable, class, change variable values, and so on.

Logic statements are also where you run you IF Conditionals, For Loops, and build your Macros; all of which we discuss a bit later.

This is the basic structure of a logic statement: {%p LOGIC and CODE IN HERE %}

Here is a real example:

{%p set my_variable = "Hello" %}

This would then create a variable with a string-type value of “Hello”. Tying this into Print statements, we could call this later with:

{{ my_variable }}

Which then prints: Hello

Note: Remember that the purpose of Logic Statements is check is conditions exists, and then pull or manipulate data to be displayed in a report template.

For a complete reference of Jinja2 syntax, visit that official documentation here: http://jinja.pocoo.org/docs/2.10/

Stripping Newlines

In Jinja, when exporting to a word document, all the logic code actually appears in the resulting word document as black spaces. The reason is that the code is read by the exporter and then replaced once its read. By default, our exported replaces with a blank newline. To prevent this, as you'll want to do in 99% of circumstances is to add a tag to all your logic statements: the letter p

{%p if my_variable == "Hello" %}
{{ my_variable }}
{%p endif %}

This will print ONLY whatever "my_variable" is assigned and the newlines that would otherwise be created from lines 1 and 3 and removed.