wearedestination / prettier-plugin-twig

Prettier Twig/HTML plugin
MIT License
4 stars 1 forks source link

Two issues with `if ... elseif ... else` formatting #6

Open BigglesZX opened 2 months ago

BigglesZX commented 2 months ago

Thanks for your work on this plugin. I've got a couple of issues with how if ... elseif ... else is formatted.

Removal of expression when using invalid else if

Describe the bug The first is a surprising removal of code when incorrectly using else if instead of elseif. This is perhaps beyond the scope of the plugin since else if isn't valid Twig, but I thought it was worth mentioning. If I use the incorrect else if instead of elseif, the expression that follows else if is removed entirely when formatting. This produces two else statements which Craft at least will error on (Unexpected "else" tag) but it's possible other implementations could allow this change to slip through undetected.

Unformatted source

{% if condition1 %}
Condition1 is truthy
{% else if condition2 %}
Condition2 is truthy
{% endif %}

Expected output

{% if condition1 %}
    Condition1 is truthy
{% else if condition2 %}
    Condition2 is truthy
{% endif %}

Actual output

{% if condition1 %}
    Condition1 is truthy
{% else %}
    Condition2 is truthy
{% endif %}

Incorrect indentation for elseif statements

Describe the bug When using elseif statements, they are indented from the if / else statements they accompany. This happens for subsequent elseif statements too, not just the first one.

Unformatted source

{% if condition1 %}
Condition1 is truthy
{% elseif condition2 %}
Condition2 is truthy
{% else %}
Something else
{% endif %}

Expected output

{% if condition1 %}
    Condition1 is truthy
{% elseif condition2 %}
    Condition2 is truthy
{% else %}
    Something else
{% endif %}

Actual output

{% if condition1 %}
    Condition1 is truthy
    {% elseif condition2 %}
    Condition2 is truthy
{% else %}
    Something else
{% endif %}

Debugging information

I've not done any development on formatters before but if you have any pointers on where to get started I'd be happy to try to put together a PR for this myself. Thanks again.

andyexeter commented 2 months ago

Hey there,

We can probably get the indentation issue sorted by replacing all instances of Liquid's elsif tag in the plugin codebase with Twig's elseif. Happy for you to submit a PR for this one if you want to take it on.

The other issue seems a bit more complex though. The heavy lifting was done by the authors of the original Shopify Liquid formatting plugin so I don't have full working knowledge of it, I've just tinkered with it and got it to do what we need after a some trial and error.