Building Components in Twig
This year, while working on a project, I was tasked with a UX overhaul of a web application built using Twig, SCSS, and PHP. With approximately 1000 Twig files in the codebase, the goal was to develop a component library that could be used easily and consistently for building user interfaces across the templates.
First Version
I began constructing the UI library by creating a custom component, CustomInput
. The natural choice was to utilize Twig Macros. Below is a snapshot of the first version of the CustomInput
component.
`
`
This version is essentially a simple Bootstrap input box with a label as the only parameter. Its usage is demonstrated below.
`
`
Second Version
While developing a Date Picker Box, I realized that I could reuse the <CustomInput>
component by adding a 'datepicker' class to the input element. However, this was challenging with the existing pattern.
To accommodate the additional class, I introduced a parameter additional_classes
, which is an array of classes.
`
`
The usage of additional classes like 'datepicker' and 'd-block' is shown in the snippet below.
`
`
Third Version
The final requirement was to handle custom HTML attributes. The previous version made it difficult to add custom attributes such as id, placeholder, and onclick.
To address this, I added an additional parameter, attrs
.
`
`
The attrs
parameter is an object containing attribute names and attribute values as key-value pairs. The usage of the final version is illustrated below.
`
`
Like what you read ? Read more Articles
Follow me on X