Create reusable HTML components with the "include" tag in TwigJS

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we take a repeating block of HTML and turn it into a dynamic, reusable TwigJS component. The "include" tag allows us to generate multiple instances of the component, each with their own custom content.

[00:00] I have a simple Gulp setup that watches from my templates folder and refreshes the browser whenever something changes. Here, we have a list of UI cards. Each have an image, a title, and a description. We currently have a block of HTML that gets repeated over.

[00:16] I'll create a new folder in my templates called components. Inside of that, I'll create a file called cards.twig. Let's get started by pasting one of the HTML blocks. I will now set some variables, so set data, and I will give it a title, a description, and an image.

[00:36] I am now able to replace my hard-coded values with our data properties. Here, data.title, data.description, and data.image. With that in place, we can now import that component in our template. Let's do that.

[00:53] I will quickly delete the first two blocks here. Twig gives us an include tag that allows us to fetch components from other files. Here, I can write components/cards.twig. Let's bring two of them. I'll save my file, and here they are.