Use the HTML preprocessor Pug to generate markup for a form. Here we generate a set of labels and checkboxes. We link these using ES6 Template Literals with a loop index.
Duration
2 min
Access
Free
Transcript
Available
Use the HTML preprocessor Pug to generate markup for a form. Here we generate a set of labels and checkboxes. We link these using ES6 Template Literals with a loop index.
Video Transcript
Jhey Tompkins: We're going to use a form for our game, so we create a form element with class name .game. A tic-tac-toe board consists of nine cells. Each of those cells provides the opportunity to either place a naught or a cross.
What we can do is use a for loop to generate 18 checkboxes. For each iteration, we create two checkboxes, input(type='checkbox'). Then we can use template literals to generate an id. Here, we're going to do x-, and then the index in the loop. We can do the same for naught with o- and the index of the loop. This will generate 18 checkboxes. We can see here the generated ids through to 8.
Next, we need an element for the board. We're going to create a div with the class name .board. This is where we're going to generate cells for the board. We can use the same for loop as before, for(let i = ; i < 9; i++).
For each iteration we're going to create a div with the class .board__cell. Inside this element we're going to create two labels to control the checkboxes. We can use the for attribute of a template literal to match up to the ids we defined for the checkboxes.
Here we have for=x-{$i} which should match up to input(type='checkbox' id=x-{$i}). Let's give our labels some text using the template literal and let's go with Cross, and we'll print out the index. We'll can do the same for Naught where we change the text to Naught and we match up the id with the o. o-{$i} goes to input(type='checkbox') id=o-{$i}).
If we look at our page, we now have 18 checkboxes and 18 labels, and clicking some labels will toggle the state for certain checkboxes.
In review, we can use Pug to generate markup for us. In this example we're using for loops. We can use template literals to generate markup based off of the index of our for loops.
Duration
2 min
Access
Free
Transcript
Available
Course lesson
Use Pug For Loops to Generate Form Markup
Use the HTML preprocessor Pug to generate markup for a form. Here we generate a set of labels and checkboxes. We link these using ES6 Template Literals with a loop index.