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 slots #6999

Open
wants to merge 2 commits into
base: 5.x
Choose a base branch
from
Open

Twig slots #6999

wants to merge 2 commits into from

Conversation

m-vo
Copy link
Member

@m-vo m-vo commented Mar 11, 2024

This introduces a new concept to our Twig ecosystem called slots. It basically allows to define placeholder sections in your templates which can be enumerated and populated at runtime. For this, we analyze the node tree at template compile time and cache the respective information for our Inspector service to use. Slots are a new language construct and as such they support some syntactic sugar for easier use (see below).

This PR builds on top of the "modern layout prototype" from #6531 and is the first step in that direction.

How it works

  1. Define "slots":

    {# @Contao/foo.html.twig #}
    <div class="wrapper">
      {# simple usage #}
      {% slot main %}{% endslot %}
    
      {# usage with placeholders #}
      {% slot left %}
          <aside>{{ slot() }}</aside>
      {% endslot %}
      
      {# using optional fallback values #}
      {% slot footer %}
          <aside>{{ slot() }}</aside>
      {% else %}
          <!-- there is no footer -->
      {% endslot %}
    </div>
  2. Introspect which slots are available:

    /** @var Contao\CoreBundle\Twig\Inspector\Inspector $inspector */
    $inspector->inspectTemplates('@Contao/foo.html.twig')->getSlots(); // ['footer', 'left', 'main']
  3. Set content for slots:

    $twig->render('@Contao/foo.html.twig', [
        '_slots' => [
            'left' => 'content for left slot',
            'main' => 'content for main slot',
        ]
    ]);
  4. Expected output:

    <div class="wrapper">
        content for main slot
        <aside>content for left slot</aside>
        <!-- there is no footer -->
    </div>

@m-vo m-vo added this to the 5.4 milestone Mar 11, 2024
@m-vo m-vo marked this pull request as ready for review March 11, 2024 23:55
Copy link
Member

@Toflar Toflar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't say much about whether the parser logic etc. is correct but the way it's used and the syntax is as discussed 😊

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

Successfully merging this pull request may close these issues.

None yet

2 participants