trivago / prettier-plugin-twig-melody

Code formatting plugin for Prettier which can handle Twig/Melody templates
Apache License 2.0
155 stars 35 forks source link

Defing a block inside a html attribute fails #60

Open andersaloof opened 4 years ago

andersaloof commented 4 years ago

In our layout.html template which all templates extend, we have the following block defined inside a html attribute:

<html class="{% block topclass %}{% endblock %}">

This code works as expected, allowing us add classes to the root HTML element inside a template, by using {% block topclass %}some-class{% endblock %}

However, prettier fails with the following error message: Expected stringEnd but found tag start "{%" instead.

A workaround is to the define the block inside a variable and use the variable in the attribute, but it's not as elegant.

{% set topclass %}
    {% block topclass %}{% endblock %}
{% endset %}
<html lang="{{ craft.app.language|replace('_','-') }}" class="{{ topclass }}">
kimili commented 3 years ago

It's not just {% block %}, it's any twig directive inside of an HTML attribute which trips up the parser. For instance, I just tried it on a link which conditionally applies an active class using an if directive, like this:

<a href="{{ page.link }}" class="section-page-link {% if page.slug == post.slug %}active{% endif %}">
  {{ page.name }}
</a>

While twig itself parses that without a problem, the parser within this plugin trips on that.

oradwell commented 3 years ago

I usually replace blocks like {% if page.slug == post.slug %}active{% endif %} with {{ page.slug == post.slug ? 'active' }} as a workaround