Jade also supports rendering lists of items as other template languages. We can use the each
construct to iterate through the elements in the array and output some HTML elements for each.
In this recipe, we're going to render a list of message objects. Each message object will have an author, arrival time, body, and read status. We're going to use a different style to distinguish between read and unread messages.
We're also going to use different backgrounds for odd and even rows.
We need to download jade.min.js
in to our recipe
folder available at https://github.com/visionmedia/jade.
Follow these steps:
index.html
containing the CSS style, placeholder, and the template script
element:<!DOCTYPE HTML> <html> <head> <title>Rendering an array with EJS</title> <style type="text/css"> .message { border-bottom:solid 1px #ccc; width: 250px; padding: 5px; } .message p { margin: 0.5em 0; } .message.unread { font-weight:bold; } .message.odd { background-color:#f5f5f5; } .message .date { float: right; font-style: italic; color: #999; } </style> </head> <body> <h2>Messages</h2> <div id="list"> </div> <script id="template" type="text/jade"> each msg,i in list .message(class=msg.status + (i % 2?' odd':' even')) p span.name=msg.name span.date=msg.date p.text=msg.text </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="jade.min.js"></script> <script type="text/javascript" src="example.js"></script> </body> </html>
example.js
to wrap the element and the template with some model data:$(function() { var template = jade.compile($('#template').html()); $('#list').html(template({list:[ { status: 'read', name: 'John', date: 'Today', text: 'just got back, how are you doing?' }, { status: 'unread', name: 'Jenny', date: 'Today', text: 'please call me asap' }, { status: 'read', name: 'Jack', date: 'Yesterday', text: 'where do you want to go today?' }, ]})); });
Besides allowing us to access the array element, the each
construct in Jade can also provide the index of the element.
Using this index we demonstrate that Jade can support arbitrary expressions. We add an odd class to oddly-numbered messages, and an even class to evenly-numbered ones. Of course, it's better to use CSS pseudo-selectors to do this, for example:
.message:nth-child(odd) { ... } .message:nth-child(even) { ... }
Jade allows us to omit the name of the element and only use a class and/or an ID attribute. In these cases the element is assumed to be a div
.
We can append CSS style classes and an ID after the element tag. Jade will add the corresponding attributes to the element.
13.58.44.229