Skip to content

Repository files navigation

Twig and Twital Components

Define reusable components in Twig/Twital as in Vue/React style.

Installation

Install this library via composer:

composer install webuni/twig-components

and enable in Twig environment:

useTwig\Environment;
useWebuni\TwigComponents\Twig\ComponentsExtension;
$twig = newEnvironment($loader, $options);
$twig->addExtension(newComponentsExtension());

Usage

Scope

Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.

Twital

Add c: prefix to a Twital attribute to indicate value as a Twig code.

Import components

vuejs/rfcs#182

TwigTwital
{% component"button.html.twig"as"button" %}
{% component"button" %}
…
{% endcomponent %}
<c:componentsrc="button.html.twig" as="button" /><c:button></c:button>

Dynamic components

https://v3.vuejs.org/guide/component-basics.html#dynamic-components

TwigTwital
{% 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>

Slots

TwigTwital
<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>

Bind

<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>

Inspiration

About

Define reusable components in Twig as in Vue/React style via Twital

Resources

Stars

0 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages