Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Twig: Whitespaces introduced with \n #616

Open
rubas opened this issue Sep 2, 2019 · 2 comments
Open

Twig: Whitespaces introduced with \n #616

rubas opened this issue Sep 2, 2019 · 2 comments

Comments

@rubas
Copy link

rubas commented Sep 2, 2019

Source

{% for term in post.get_terms('post_tag') %}
    <span>{{ term.name }}</span>{% if not loop.last %}, {% endif %}
{% endfor %}

Result after beautify

{% for term in post.get_terms('post_tag') %}
    <span>{{ term.name }}</span>
    {% if not loop.last %},
    {% endif %}
{% endfor %}

Problem

The source is rendered as foo, bar, baz while the beautified version is foo , bar , baz.

The new line introduces one whitespace after the <span>.

Honestly I'm not sure what to do here. I see that for HTML you only add a new line, if there is at least one whitespaces after a tag. But applying the same logic to Twig Tags would limit the optimisation options {% if...%}{% if ... }..{% endif %}{% endif %}

Fix

We have to use the "Tag level Line whitespace control" explicitly.

{% for term in post.get_terms('post_tag') %}
  <span>{{ term.name }}</span>
  {%- if not loop.last -%},
  {%- endif -%}
{% endfor %}

https://twig.symfony.com/doc/2.x/templates.html#whitespace-control

@prettydiff
Copy link
Owner

Since there is a Twig solution to this issue would you like me to continue to work this? This would be a very challenging problem to solve for.

@rubas
Copy link
Author

rubas commented Sep 3, 2019

Yes, as a beautifier should never change the rendered result. Introducing prettydiff to an existing Twig codebase can result in a change of the rendered output, which is not easy to catch.

No, as I'm not sure, if this problem is solvable or if we just have to adjust the pattern on our side.


We can differentiate between Twig Control structures {% ... %}, Twig Content {{ ... }} and Content in general.

As long as there is at least one whitespace between the last Twig Content / Content and the next Twig Content / Content, introducing a new line is fine.

Only if there is absolutely no whitespace between, we get an issue with adding a line break between.

It's the same situation as we HTML but with the added complexity of the Twig Tags.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants