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

Already subscribed? Sign In


    Make your HTML components dynamic with the "with" keyword in TwigJS

    Simon VrachliotisSimon Vrachliotis
    htmlHTML 5

    In this lesson, we make TwigJS components output custom content via the "with" keyword of the "include" tag. We also set up fallback values to make our component work in a variety of scenarios.



    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


    00:00 I am including two instances of a card component as defined in the cards.twig partial. The include tag in Twig allows you to pass custom data via the with keyword. Here, we'll give it a title, a description, and an image.

    00:16 Let's refactor our component inaudible . I'll rename our data variable to fallback and create a new data object. If the title is defined in my component, then use the title. If not, use the fallback version of the title instead. If the title is passed through the include tag, it will use that. If not, it'll use the fallback value.

    00:38 Same process for the description and for the image, since we passed custom values, we can see the new image and text here while the other component is outputting the fallback values, in our first component here, let's add an image, but no title and no description.

    00:56 Now, you will see the image updated here, but the title and description will keep the fallback values. Let me quickly delete these static HTML blocks. I'll duplicate my first include tag a couple of times with different images, give a title to this one of "How Cool Is This?"

    01:11 Now, you have a pretty robust setup. You can create cards on the fly with only one single block of HTML to maintain. Say you want to change the title to light red, font weight 900, change it in one place, and this is updated everywhere.