Search code examples
symfonytwigfrontendtwig-extension

Twig and atomic pattern — Clean twig rendering


I'm trying to follow the atomic design pattern with twig.

When rendering a simple atom, I need to do something like:

{% include '@MyBundle/Resources/views/atoms/button/button.html.twig' with { href: '/section1', text: 'Example text' } only %}

This approach starts getting messy when the atom or component has more variables, or the directory structure is a bit more complex.

I'd be awesome to be able to do something like:

{% button('/section1','Example text') %}

I know that this can be achieved with a twig function, but I'm worried this pattern can get tricky with a larger code base.

Any experience around this? Cheers!


Solution

  • You can use macro structure. Read documentation: http://twig.sensiolabs.org/doc/tags/macro.html

    {% macro button(href, text) %}
        {% here you can place your template %}
    {% endmacro %}
    

    Then you will need only import your twig file with macro once. After that you can use construction like {% button('/section1','Example text') %}.