Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

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

    Simon VrachliotisSimon Vrachliotis
    htmlHTML 5

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    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.

    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.

    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.

    Discuss

    Discuss