re: Emulating Components in Twig VIEW POST


Using Macros satisfied one criterion, passing props, but it didn't solve my problem of wanting to pass markup into my "component" via named slots.

You can easily pass whole chunks of HTML to a macro by storing that HTML in a variable, pass it to the macro and output with the raw filter.

To define a variable storing markup, you can use an extented form of the set command e.g.

{% set slotContent %}
  <h1>My markup</h1>
{% endset %}

I don't know if I'm doing it right, but I used only macros to build a library of around 50 components I deliver frequently with updates to the back-end developers using some form of Symfony framework.

Also I used Patternlab Twig Edition to develop the components decoupled from the application that will use it.


Hey René!

Yeah, this solution totally works! Here are a few reasons I prefer using Embeds over this:

  1. Embeds are more readable: It's easier to read the {% block %} syntax within an embed than it is to see one (or multiple) statements setting HTML to a variable, and then passing those variables into a Macro.
  2. The syntax for outputting the blocks of content (within the embed declaration, is cleaner with embeds. This is especially true if you want to set defaults.

There may be other reasons, but these are the ones that come to mind.

All of that said, the way you're doing it isn't "wrong" and I'm glad you found a way to accomplish what you needed to!

code of conduct - report abuse