The goal of the code is to make the list of item written correctly. As an example, if you have 2 windows that are open, it will be written Window 1 and Window 2
. However, if you have more than 2, it will be written Window 1, Window 2, and Window 3
.
If you paste {{ windows.split(', ') }}
in Developer Tools → Template will result in ['Window 1', 'Window 2', 'Windows 3']
. Notice that there are 3 elements - Window 1 is the first element, Window 2 is the second element, and Window 3 is the third element.
Next, we want to know if there are 2 or more items. If there are only 2 items, we want to combine it using and
. However, if there are more than 2, we want to combine the latest one using , and
.
Therefore, you use | count
in {% set x = ', and ' if windows.split(', ') | count > 2 else ' and ' %}
. If there are only 2 element, x
will be and
, if more than 2 element, x
will be , and
.
If you paste {{ windows.rsplit(', ', 1) }}
in Developer Tools it will result in ['Window 1, Window 2', 'Window 3']
. Notice that there are only 2 elements - 'Window 1, Window 2'
is the first element, while 'Window 3'
is the second element.
The basic syntax is string.rsplit(separator, maxsplit)
. By setting the maxsplit
to 1, it will only return a list with 2 elements (just like the above example).
Why do we need it? Because we want to join the x
just before the last element.
Therefore, we use x.join(windows.rsplit(', ', 1))
to join it.
Sorry, I made a mistake here-
It should be-
Alert! {{x.join(windows.rsplit(', ', 1))}} {{'are' if windows.split(', ') | count > 1 else 'is' }} open in the living room.