Forum Discussion
DougHenning1
2 years agoCommunity Manager
Thank you for making the video and sharing your knowledge with others! For the sake of learning, I'd like share some improvements you can make to the Jinja for more streamlined code.
1. Try not to use variables that are also the names of filters (
2. The namespace functionality is very useful, but in your case you don't actually need it. I assume you're using it because some lines may be blank and you don't want to count them. If you filter the list to exclude the blank lines then you can just use the loop index instead:
Here's the complete updated code:
------------------------------
Doug Henning
------------------------------
1. Try not to use variables that are also the names of filters (
list
is a filter). While it will work most of the time, it can cause confusion.2. The namespace functionality is very useful, but in your case you don't actually need it. I assume you're using it because some lines may be blank and you don't want to count them. If you filter the list to exclude the blank lines then you can just use the loop index instead:
{% for x in plist if x|trim != '' -%}ā
3. Use the variable specified in the for loop (x
) instead of list[loop.index0]
4. You can use loop.last to see if you need to add the comma:
{{ ',' if not loop.last }}
Here's the complete updated code:
{% set plist = a.quick_capture.split('\n') -%}
{
"to": "br8hpcpk7",
"data": [
{% for x in plist if x|trim != '' -%}
{
"18": { "value": "{{a.related_director}}" },
"89": { "value": "{{a.id}}" },
"6": { "value": "{{loop.index}} {{ x|trim }}" }
}{{ ',' if not loop.last }}
{% endfor -%}
]
}
Thanks again for sharing and hope this helps!
------------------------------
Doug Henning
------------------------------