trivago / melody

Melody is a library for building JavaScript web applications.
https://melody.js.org
Apache License 2.0
215 stars 39 forks source link

Introduce generic twig tags #154

Closed twbartel closed 4 years ago

twbartel commented 4 years ago

The main thing about this merge request is that it adds parsing capability for arbitrary Twig tags. This capability is activated through an option allowUnknownTags.

Background: If we only want to parse a Twig file, without executing it, we don't need custom parsers for all kinds of Twig tags. In this case, Melody can generate AST nodes of type GenericTwigTag for Twig tags it does not know.

This is good enough for "lone" Twig tags like {% exit 404 %}. However, sometimes, pairs or even groups of Twig tags belong together. Example:

{% nav entry in entries %}
    <li>
        <a href="{{ entry.url }}">{{ entry.title }}</a>
        {% ifchildren %}
            <ul>
                {% children %}
            </ul>
        {% endifchildren %}
    </li>
{% endnav %}

Here, {% nav %} and {% endnav %}, as well as {% ifchildren %} and {% endifchildren %} belong together.

In order to have such tags adequately represented in the AST, they have to be made known to the Melody parser beforehand. The new option multiTags is used for that:

{
    allowUnknownTags: true,
    multiTags: { 
        nav: ['endnav'],
        ifchildren: ['endifchildren'],
        switch: ['case', 'default', 'endswitch']
    },
}

multiTags is an object whose keys are the tag names of the first in a sequence of tags (here, nav and ifchildren), and whose values are arrays containing the other tag names that can occur in the sequence. It's important that the concluding tag name comes last in this array. Other than that, the order does not matter.