giorgiopogliani / twig-components

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

Add dynamic component #25

Closed Pindagus closed 5 months ago

Pindagus commented 5 months ago

Adds a dynamic component like Blade's dynamic component and closes #24

This works but the code feels a bit messy. Any feedback to clean this up will be appreciated! Also, if it works it works right? :joy:

giorgiopogliani commented 5 months ago

Actually, I think we can skip changes the in ComponentTokenParser.php if you create the compiled php. I mean instead of returning the path you got with regex. Have you tried literally return "'/' . $context['component'] . '.twig'" as a string?

I am not 100% sure that the $context contains the variables/attributes, I don't remember. But, you don't need to parse the attributes, you can still get the variables node with $this->getNode('variables') this should return like a twig node array or something... and you should find the component attribute there.

Also, if you could add a test it would be great. TIP: During testing If you uncomment the cache param in the tests and run indivually the test you can see the generated php class templates.

btw thanks for this cool feature!

Pindagus commented 5 months ago

The regex part is actually just a messy way to get the component variable, which can also be retrieved within the ComponentNode as you suggest.

The getTemplateName() already returns a string which is actually "compiled" PHP. I am only replacing the dynamic-component part in the path with the context variable, because my setup uses another base path and no .twig extension. So this would work with different settings.

I'll look into cleaning things up and keeping the changes inside the ComponentNode. Will also add a test while I'm revising.

Thanks for the feedback!

Pindagus commented 5 months ago

Todo:

Pindagus commented 5 months ago

@giorgiopogliani I think this is done unless you have other cases we should test against. I hope the changes are somewhat understandable. Will document if you find any changes that are unclear.

giorgiopogliani commented 5 months ago

Looks good! I'll merge it and tag a new version.