Fixed #18400 Unexpected {% if %} behavior in templates.

Thanks Florian for the bug report, luyikei for the initial code patch, and
Bouke for the code review feedback.