Common use cases
Check if a field is defined (exists)
The example below checks if an API response and an id exists. If the statement is true then the id is returned.
{% if response and response.id %}
{{ response.id }}
{% else %}{% endif %}
If the response id is nested in another JSON value, the above statement can be modified to:
{% if response and response.collection and response.collection.id%}
{{ response.collection.id }}
{% else %}{% endif %}
Check if a field is not empty
You can use a similar check to determine if a field is not empty:
{% if response and response.id|length %}
{{ response.id }}
{% else %}{% endif %}
Join or group fields
It may be necessary to join or group fields, for example, you might wish to group all assets belonging to a user. The below template can be used in a workflow block to group or join items in a list.
{% if response %}
{{ response|map(attribute='model') | list | join(', ') }}
{% else %}{% endif %}
In the example below, the response will be: Macbook Pro, Dell.
[ { "equipment_id": "123", "model": "Macbook Pro", } { "equipment_id": "456", "model": "Dell", } ]
Change case
You can also add custom Jinja2 to your workflow block to clean or modify the data that is returned in an API response. For example, you could use upper()
lower()
or capitalize()
to convert a value to uppercase or capitalize the first letter in a value.
{% if response and response.name|length %}
{{ response.name.upper()}}
{% else %}{% endif %}
Or combine the Python syntax and Jinja filters to return the first letter of the full name in upper case:
{{full_name.split() | first | capitalize}}
Replace or edit text
Use the following Jinja syntax to replace or modify text.
{{barcode.replace('LX', 'XX')}} *Replaces one string with another
{{barcode.strip('LX')}} *Removes a string
{{barcode.zfill(10)}} *Prepends a string with'0'
to make a string of length 10
{{barcode[::-1]}} *Reverses the text, i.e. Jane becomes enaJ
Change the date format
Use the following Jinja syntax to convert a date (called Hire Date) from mm/dd/YYYY to YYYY/mm/dd format.
{% set datetime = import('datetime') %}
{{ datetime.datetime.strptime(hire_date|string, '%m/%d/%Y').strftime('%Y-%m-%d') }}
Documentation
Jinja: Template Designer Documentation
Python Documentation (for supported string methods)
Comments
0 comments
Please sign in to leave a comment.