set-hello-badge-2-repetition v0.0.5
Set Hello Badge Tutorial: Repetition (Part 2 of 4)
In Part 1, we used the Set template engine (Git it now!) to create a name badge that displays your name and links it to her web site.
In this example, we’re going to build on that and make lots of labels.
Usage
- Clone the repository.
- Run
npm install
to install the dependencies. - Run
npm start
to start the server.
Once the server is running, go to http://localhost:3000
to see the example and http://localhost:3000/hello-badge.html
to see the template source.
Read the notes below to find out how it works and take a peek at the source code.
How it works
Templates in Set are pure HTML 5. Set uses data-
attributes to populate templates either on the server or on the client (or both).
One of those attributes, data-set-repeat
lets you to repeat a DOM element multiple times by looping over an array in the data.
The template
Let’s modify the hello-badge.html
template so that our name badge is wrapped up in a list. Each list item will be repeated and become a new badge.
<ul>
<li data-set-repeat='person people'>
<a data-set-attribute='href person.homepage'><p>Hello, my name is <span data-set-text='person.name'>Inigo Montoya</span></p></a>
</li>
</ul>
With the attribute data-set-repeat='person people'
we are saying ‘repeat this node for each person in the people array’.
That’s the only change we need to make in the HTML.
The server
The only thing we need to change in the server is the data object that we’re passing to Set. We create an array of people in it, where each person has name and homepage properties.
express = require 'express'
set = require 'set'
app = express()
app.engine 'html', set.__express
app.set 'view engine', 'html'
app.use express.static('views')
data = {
people: [
{ name: 'Aral', homepage: 'https://aralbalkan.com' }
, { name: 'Laura', homepage: 'http://laurakalbag.com' }
, { name: 'Jo', homepage: 'http://www.jo-porter.com' }
, { name: 'Osky', homepage: 'http://twitter.com/gigapup' }
]
}
app.get '/', (request, response) ->
response.render 'hello-badge', data
app.listen 3000
That’s it!
When you run the example, four badges will be created.
Continue learning about Set in Part 3: Conditionals.
Table of Contents
- Part 1: Text and Attribute
- Part 2: Repetition
- Part 3: Conditionals
- Part 4: Dummy Data
This is just a very simple example. Check out the Set web site for more complicated ones.