giorgiopogliani / twig-components

Twig components inspired from blade components
MIT License
71 stars 16 forks source link

feat: support twig namespaces with `:` in component name #9

Closed kurtrank closed 3 years ago

kurtrank commented 3 years ago

I recently discovered this extension while looking for a 'slots' solution in twig, which this extension does very well. I am working on integrating twig-components into a project that allows plugins to register additional components, so they might not all be stored in one main directory. Initially I tried out initializing the plugin by passing a twig namespace as the component directory, like @components, which actually works decently well on its own. I can continue to register additional template directories under that namespace and reference twig files in any of them. This is just a project for my immediate team (for now), but I do see complications if more than one plugin inadvertently adds a twig template with the same filename.

In order to prevent this, I think it would be useful to be able to optionally specify a namespace along with the component name in the opening block tag. When including a component, the component name can contain one : which allows a twig namespace to be specified. Example: {% x:namespace:component.name %}

{# includes '@mds/accordion.twig' #}

{% x:mds:accordion with {title: 'Twig Components'} %}
    {% slot:content %}<p>Are Awesome!</p>%{ endslot %}
{% endx %}
{# or #}
<x-mds:accordion title="Twig Components">
    <x-slot name="content"><p>Are Awesome!</p></x-slot>
</x-mds:accordion>

I was not too familiar with how twig actually parsed everything, but I did some research and took a look at how the parser in twig-components works and ended up making a couple small additions:

I saw one issue that mentioned namespaces, but it was primarily about subdirectories. I considered trying to use that but to me it makes sense to take advantage of a feature twig has rather than having to nest files in an extra folder level. I made more progress than I originally thought I would, so I figured I would submit it as a PR and start a discussion about how useful others would find this.

giorgiopogliani commented 3 years ago

Looks good!

kurtrank commented 3 years ago

@giorgiopogliani Thanks! That's a really good point, I had not tested the :attr expression syntax with the x-tags. I went ahead and created some tests that include that as well as a couple other variations, and they all look good. I have also added a section to the readme with a short explanation as well.