Jinja Syntax and Examples for Configuration Templates - TechLibrary (2023)

CSO configuration templates consist of three components:

  • A Jinja template configuration, which contains the logicand the configuration for the configuration template. (Jinja is atemplate engine for Python and you can find several Jinja resourceson the Web.)

  • A Yang data model file, which contains the descriptorsfor the configuration schema.

  • A ViewDef (view definition) file, which is a JavaScriptObject Notation (JSON) file that is used to specify the GUI aspectsof the configuration template.

When you use the Add Configuration Template workflow to adda template, you specify the template configuration and logic by usingthe Jinja template language. CSO then generates the Yang data modeland the ViewDef files automatically based on template configurationand logic that you specified. The generation of the Yang and ViewDeffiles is transparent to the user and doesn’t require any userintervention.

Jinja Syntax and CSO Keywords

The tables below list the Jinja syntax used commonly in configurationtemplates and the keywords used in configuration templates respectively.

Table 1: Common Jinja Syntax Used in Configuration Templates

Syntax

Explanation

{{ }}

Denotes a variable or expression that will be printed to thetemplate output. For example:

{{tenant_name}}

Note:Hyphens are not recognized by the CSO template engine, so useunderscores (_) in variables or expressions.

{# #}

Denotes a comment that will not be included in the templateoutput. For example:

{# This is an example of comment in Jinja syntax #}

{% %}

Denotes statements that are used to create conditional logic:

  • The {%- -%} statement removeswhitespace characters from the output.

  • The if statement used to executea set of commands (enclosed between the if and endif keywords) when the conditionis true.

    {% if <condition> %}.........{% endif %}
  • The if-else statements are used to execute a set of commands (enclosed betweenthe if and else keywords) when the condition is true and a different set of commands(enclosed between the else and endif keywords) when the condition is false.

    {% if <condition> %}......{% else %}......{% endif %}
  • The for statement is used toloop through a set of commands (enclosed between the for and endfor keywords)when the condition is true.

    {% for <condition> %}........{% endfor %}

Dot (.)

A dot [operator] is used to reference an attribute of a variable.The following example shows a for loopwhere you can add multiple prefixes:

{% for prefix in Trusted_Network_Prefix_List %}set groups trusted‐prefix policy‐options prefix‐list re‐ssh {{prefix.Trusted_Network_Prefix_List}}{% endfor %}
Note

You can use configuration template keywords if you enable advancedmode for the configuration template.

Table 2: Configuration Template Keywords

Keyword

Explanation

post_config

Indicates to CSO that the variable that follows is a data type.

pre_config

Indicates to CSO the current configuration associated with adevice. The pre_config keyword is used to compare a variable field’svalue and then modify or delete existing configuration from a targetdevice.

diff_config

Indicates to CSO that the pre_config and post_config shouldbe compared and that CSO should create a new rendered configurationand then push it to target device.

Example 1: Convert a Single Junos OS Command to Jinja Syntax

If you want to convert a single Junos OS command into Jinjasyntax for use in a configuration template:

  1. Identify the variables that are configured in the JunosOS command.

    For example, in the command set snmp trap-group CSO-Trp-Grptargets 192.0.2.100, the variables configured are CSO-Trp-Grpand 192.0.2.100.

  2. Convert the Junos OS CLI command to Jinja syntax by enclosingeach variable in double curly braces as follows: {{ Variable_Name }}.

    So, in this example, if we use Trap_Group_Name and SNMP_Host_IP_Address as the variable names,the Jinja syntax for the command is as follows:

  3. If you paste this in the Template Configuration sectionof the Add Configuration Template workflow, CSO detects the parametersas follows:

    Parameters

  4. If you use the preview feature to render the configuration(for an OpCo named Juniper and a configuration template named Test),using the values indicated in the first step, CSO renders the configurationas follows:
    (Video) Salt Formulas Working Group 2021-FEB-09

    Notice that although you provided the JInja syntax for a singleJunos OS command, CSO added additional commands to the configuration.This is because, by default, CSO uses Junos OS groups to generatethe configuration. Junos OS groups make it easier to apply and deleteconfigurations. For more information, see Understanding Junos OS Configuration Groups.

    If you don’t want to use Junos OS groups, you must turnon the advanced mode in the configuration template, when you specifythe configuration in Jinja syntax..

Example 2: Convert a Junos OS Configuration Snippet to JinjaSyntax

In this example, we’ll convert the following Junos OSconfiguration snippet into Jinja syntax for use in a configurationtemplate:

set forwarding-options dhcp-relay server-group DHCP-SERVER192.0.2.50

set forwarding-options dhcp-relay active-server-group DHCP-SERVER

set forwarding-options dhcp-relay group CSO-Relay-Grp1 interfacege-0/0/2.0

set security zones security-zone trust host-inbound-trafficsystem-services dhcp

To convert the Junos OS configuration into Jinja syntax:

  1. Identify the variables that are configured in the JunosOS commands. For ease of understanding, the variables are enclosedwithin angular brackets (<>) in the example below.Note

    In this example, we’re not considering DHCP-SERVER asa variable.

    set forwarding-options dhcp-relay server-group DHCP-SERVER<Relay_IP>

    set forwarding-options dhcp-relay active-server-group DHCP-SERVER

    set forwarding-options dhcp-relay group <Relay_Group_Name> interface <Relay_Interface>

    set security zones security-zone <Relay_Zone> host-inbound-traffic system-services dhcp

  2. Convert each Junos OS CLI command to Jinja syntax by identifyingthe variables, providing a name for each variable, and enclosing eachvariable in double curly braces. So, in this case, the Jinja syntaxis as follows:
  3. When you paste this in the Template Configuration sectionof the Add Configuration Template workflow, CSO detects the parametersas follows:

    Parameters

  4. If you use the preview feature to render the configuration(for an OpCo named Juniper and a configuration template named Test),using the values for this example, CSO renders the configuration asfollows:

Example 3: Use Conditional Logic

In this example, which is a modified version of the precedingexample, we’ll see how you can use conditional logic (if and for statements) ina configuration template.

The explanation of the example above is as follows:

  1. In this example, we add an if statement and enclose the configuration within that statement asfollows:

    This means that the configuration is applied only if the enable_Forwarding_Optionsis True. If enable_Forwarding_Options is False, then no configurationis applied.

    Tip

    If you want to apply a different configuration when enable_Forwarding_Optionsis False, you can use the else statement.

  2. Then, we add a for statementto enable the configuration of more than one set of values for the Relay_Group_Name, Relay_Interface, and Relay_Zone variables.

    When you use a for statement, theGUI rendered by CSO (when you use the preview feature) displays thevariables in table (grid). You can then use the Add icon (+) to add rows to the table and configure one or more sets of valuesas needed.

  3. When you paste the Jinja commands in the Template Configurationsection of the Add Configuration Template workflow, CSO detects theparameters as follows:

    Parameters

  4. If you use the preview feature to render the configuration(for an OpCo named Juniper and a configuration template named Test),and provide values for the parameters, including two sets of valuesfor Relay_Group_Name, Relay_Interface, and Relay_Zone, CSO renders the configurationas follows:

Example 4: Use Variable Substitution

In this example, we use a variable as part of the configurationcommand such that the value that we specify forthe variable is used in the command.

The explanation of the example above is as follows:

  1. We use the VLAN_Id attributeof the pool parameter to set the JunosOS configuration parameters vlans and vlan-id.
  2. When you paste the Jinja command set groupsMIST vlans V-{{pool.VLAN_Id}} vlan-id {{pool.VLAN_Id}} in the Template Configuration section of the Add Configuration Templateworkflow, CSO detects the parameters as follows:

    Parameters

    This is because we’ve used the dot (.) operator to referencethe attribute VLAN_Id of the parameter pool.

  3. If you use the preview feature to render the configuration(for an OpCo named Juniper and a configuration template named Test),and provide the value 120 for VLAN_Id,CSO renders the configuration as follows:

    In the rendered configuration command, you can see that theparameters vlans and vlan-id are set to V-120 and 120 respectively, based on the value thatwe provided for the VLAN_Id parameter.

Example 5: Use Filters, Concatenation, and Set Variables

In this example, we’ll look at how to set a variable usingconcatenation and filters, and then use that variable in a Junos OSconfiguration command.

The explanation of the example above is as follows:

  1. The Jinja statement {% set pool_name = Dhcp_Server_Name+ ’_’ + Interface | replace(“/”,”_”)%} is used to set a variable called pool_name, using two other variables Dhcp_Server_Name and Interface, as follows:
    1. The | (pipe) operator is usedto separate variables from filters, which are functions that modifyvariables. In this example, we use the replace(“/”,”_”) filter to modify the Interface variable byreplacing the / (forward slash) characters with _ (underscore) characters.
    2. Then, we use the + operatorto concatenate the resulting string with the variable Dhcp_Server_Name.Note

      The operator + is typically usedto add numbers, but when the values are strings, the strings are concatenated.

    3. Finally, the tag set is used(along with the = operator) to set thevariable called pool_name to the concatenatedvariable.
  2. Then, the Junos OS command set system servicesdhcp-local-server overrides process-inform pool {{pool_name}} is used to configure the Junos OS configuration statement pool using the variable pool_name that weset in the preceding step.
  3. When you paste the Jinja commands in the Template Configurationsection of the Add Configuration Template workflow, CSO detects theparameters as follows:

    Parameters

    As you can see, the Junos OS command or the pool_name variables are not displayed because we’re using the Interface and Dhcp_Server_Name variablesto arrive at the final Junos OS configuration.

  4. If you use the preview feature to render the configuration(for an OpCo named Juniper and a configuration template named Test),and provide the values LA_dhcp_srvr for Dhcp_Server_Name and ge-0/1/2 for the Interface, CSO rendersthe configuration as follows:

    As explained in a previous step, the / characters in ge-0/1/2are first replaced with _ characters, which changes the string toge-0_1_2. This string is concatenated with LA_dhcp_srvr to producethe string LA_dhcp_srvr_ge-0_1_2, which is used in the Junos OS configurationcommand.

    Therefore, the Junos OS configuration command generated is set system services dhcp-local-server overrides process-inform poolLA_dhcp_srvr_ge-0_1_2.

Example 6: Test a Value

In this example, we’ll look at how to test a value andperform actions based on the result of the test conditions.

The explanation of the example above is as follows:

  1. We test the parameter NewNetwork.VLAN_Id for two conditions:
    1. Whether the parameter is defined (by using the NewNetwork.VLAN_Id is defined condition)

    2. Whether the length of the parameter is greater than two(by using the condition (NewNetwork.VLAN_Id | count)> 2)

    Because we use the keyword and:

    • The configuration command set vlan-id {{NewNetwork.VLAN_Id}} is added to the configuration (that CSO generates) when both conditions hold true.

    • The configuration set vlans VL-{{NewNetwork.VLAN_Id}} is added to the configuration when either of the conditions is false.

  2. When you paste the Jinja commands in the Template Configurationsection of the Add Configuration Template workflow, CSO detects theparameters as follows:

    Parameters

  3. If you use the preview feature to render the configuration(for an OpCo named Juniper and a configuration template named Test),and:
    • Provide the value 125 for VLAN_Id, CSO renders the configuration as follows becauseboth conditions are true:

    • Provide the value 65 for VLAN_Id, CSO renders the configuration as follows becauseone of the conditions is false (length of the parameter is not greaterthan 2):

Related Documentation

  • Add Configuration Templates

FAQs

What are Jinja templates used for explain with example? ›

It is a text-based template language and thus can be used to generate any markup as well as source code. The Jinja template engine allows customization of tags, filters, tests, and globals. Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects.

What is {%- syntax in Jinja? ›

Jinja Syntax and CSO Keywords

The {%- -%} statement removes whitespace characters from the output. The if statement used to execute a set of commands (enclosed between the if and endif keywords) when the condition is true. {% if <condition> %} ... ... ... {% endif %}

What is the format of Jinja template? ›

A Jinja template is simply a text file. Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: . html , .

How to check Jinja template in Python? ›

Primer on Jinja Templating
  1. Get Started With Jinja. Install Jinja. Render Your First Jinja Template. ...
  2. Control the Flow in Jinja. Use if Statements. ...
  3. Use Jinja With Flask. Install Flask. ...
  4. Nest Your Templates. Adjust Your Base Template. ...
  5. Apply Filters. Adjust Your Menu Items. ...
  6. Include Macros. Implement a Dark Mode. ...
  7. Conclusion.

What are templates give an example? ›

A template is a form, mold or pattern used as a guide to make something. Here are some examples of templates: Website design. Creating a document.

What is {{ }} in Jinja? ›

{%....%} are for statements. {{.... }} are expressions used to print to template output. {#....#} are for comments which are not included in the template output.

What is syntax for code? ›

Syntax is the set of rules that define what the various combinations of symbols mean. This tells the computer how to read the code. Syntax refers to a concept in writing code dealing with a very specific set of words and a very specific order to those words when we give the computer instructions.

What is syntax format? ›

Syntax Formatting uses rich text formatting based on program information. Source Insight uses information gathered from its parsers to format source code. Identifiers can be displayed in different fonts or font sizes, along with a variety of effects such as bold and italics.

What is templating syntax? ›

The template syntax helps guide us on how to control the user interface and user experience by coordinating data between the class and the template. There are designed attributes and elements for writing an angular template.

Which three features are included in the Jinja2 templates? ›

Jinja2 Features:
  • Sandboxed execution.
  • Powerful automatic HTML escaping system for XSS prevention.
  • Template inheritance.
  • Compiles down to the optimal python code just in time.
  • Optional ahead-of-time template compilation.
  • Easy to debug. ...
  • Configurable syntax.
Jun 17, 2020

Where does Jinja look for templates? ›

The simplest way to configure Jinja to load templates for your application is to use PackageLoader . This will create a template environment with a loader that looks up templates in the templates folder inside the yourapp Python package (or next to the yourapp.py Python module).

How do I create a list in Jinja? ›

You initialize a list using the {% set myList = %} notation, as with ordinary variables. However, to tell the renderer that you are initializing a list, you need to use the square-brackets notation for lists. In between the square brackets, you can specify the values that your list will contain from the get-go.

How do you pass variables to Jinja? ›

Jinja expects this variable to be provided to the engine by you and it simply takes the value referred by the variable replacing {{ name }} statement with that value. In other words, Jinja just substitutes the variable name for its value. That is the most basic component you'll be using in your templates.

What is block content in Jinja? ›

Many of the Jinja functionalities reside as code blocks. These blocks are usually declared as: {% blocktype %} ... {% endblocktype %} . Code blocks not only enable you to organize your code better visually, but they also allow you to semantically divide your code into coherent blocks that provide one certain function.

Can you use Python functions in Jinja? ›

Using a Python function in a Jinja template

These functions are placed in a dictionary. After this, the render function is created. Inside this function, we use jinja_template. globals.

What is the use of Jinja template in Flask? ›

Flask uses templates to expand the functionality of a web application while maintaining a simple and organized file structure. Templates are enabled using the Jinja2 template engine and allow data to be shared and processed before being turned in to content and sent back to the client.

What is the advantage of using Jinja? ›

Code Reusability

One of the key benefits of using Jinja templates is the ability to reuse code across multiple pages. This can save you time and effort when creating complex web applications. To achieve code reusability in Jinja, you can use macros and include statements.

What are templates used for? ›

Templates are pre-formatted documents designed to create commonly used document types such as letters, fax forms, or envelopes. Some of the advantages of using templates are: Templates simplify the creation of documents.

How to use Jinja template in Python? ›

Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %}. You can optionally include both {% elif %} and {% else %} tags, and for loop, we use {% for index in numbers %} and end with {% endfor %}.

Top Articles
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated: 30/08/2023

Views: 6186

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.