Define reusable components in Twig/Twital as in Vue/React style.
Install this library via composer:
composer install webuni/twig-componentsand enable in Twig environment:
useTwig\Environment;
useWebuni\TwigComponents\Twig\ComponentsExtension;
$twig = newEnvironment($loader, $options);
$twig->addExtension(newComponentsExtension());Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.
Add c: prefix to a Twital attribute to indicate value as a Twig code.
| Twig | Twital |
|---|---|
{% component"button.html.twig"as"button" %}
{% component"button" %}
…
{% endcomponent %} | <c:componentsrc="button.html.twig" as="button" /><c:button>
…
</c:button> |
https://v3.vuejs.org/guide/component-basics.html#dynamic-components
| Twig | Twital |
|---|---|
{% component"button.html.twig"as"button" %}
{% component"group_button.html.twig"as"group_button" %}
{% componentcurrent_component %}
…
{% endcomponent %} | <c:componentsrc="button.html.twig" as="button" /><c:componentsrc="group_button.html.twig" as="group_button" /><c:componentc:is="current_component">
…
</c:component> |
| Twig | Twital |
|---|---|
<ul>
{% forindex, iteminitems %}
<li>
{% slotbind"item" %}{{ item }}{% endslot %}
</li>
{% endfor %}
</ul>{% component"todo-list" %}
{% templatebind"slot_context" %}
<iclass="fas fa-check"></i>
<spanclass="green">{{ slot_context.item }}<span>
{% endtemplate %}
{% endcomponent %}{% component"todo-list" %}
{% templatebind"{item}" %}
<iclass="fas fa-check"></i>
<spanclass="green">{{ item }}<span>
{% endtemplate %}
{% endcomponent %} | <ul><lit:for="index, item in items"><c:slotbind="item">{{ item }}</c:slot></li></ul><c:todo-list><c:templatebind="slot_context"><iclass="fas fa-check"></i><spanclass="green">{{ slot_context.item }}<span></c:template></c:todo-list><c:todo-list><c:templatebind="{item}"><iclass="fas fa-check"></i><spanclass="green">{{ item }}<span></c:template></c:todo-list> |
<c:slotbind="item"></c:slot><c:slotbind="item = item"></c:slot><c:slotbind="{item}"></c:slot><c:slotbind="{item: item}"></c:slot><c:templateslot="header" bind="item"></c:template><c:templateslot="default" bind="item = item"></c:template><c:templatebind="{item: item}"></c:template>Multiple
<c:slotbind="item, key"></c:slot><c:slotbind="item = item, key = key"></c:slot><c:slotbind="{item, key}"></c:slot><c:slotbind="{item: item, key: key}"></c:slot>Dynamic bind
<c:slotc:bind="{(item): 'item'}">{{ item }}</c:slot>