Jade is a clean, terse template language. It uses significant whitespace to denote block and element hierarchy. It supports many advanced features, for example, mixins, which are subtemplates and blocks, which are template sections replaceable by inheritance.
In this recipe, we're going to render a simple greeting using Jade. Later on in this chapter, we're going to look at some of the more advanced features.
We need to download jade.min.js
in our recipe
folder, available at https://github.com/visionmedia/jade.
Let's get started.
index.html
, it will contain a small form asking the user for his or her name, a placeholder to render the greeting, and the greeting template:<!DOCTYPE HTML> <html> <head> <title>Displaying an object with Jade </title> </head> <body> <form method="post"> <p>Name: <input id="name" type="text" name="name" value="John"></p> </form> <div id="greeting"> </div> <script id="template" type="text/jade"> if hour > 18 span Good evening, else if hour < 10 span | Good | morning, else span Hello, b= name </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 compile the template and bind it to the data and the view:$(function() { var template = jade.compile( $('#template').html() ); function changeName() { $('#greeting').html(template({ name: $("#name").val(), hour: new Date().getHours() })); } $('#name').on('keypress keyup', changeName); changeName(); });
Jade templates are very similar to the resulting HTML structure. Our template produces a single span
element containing the greeting text, and another b
(bold) element containing the name of the user.
Jade supports conditionals. Their syntax looks exactly similar to the element syntax, except that they're not rendered. The condition doesn't need to be wrapped in parenthesis, but otherwise the Boolean expression is evaluated as the JavaScript code.
As shown in the "Good Morning" greeting, we can use the vertical pipe character to split the text into multiple lines
To display the contents of a variable (escaping HTML markup), we use the "=
" (equals) character. If we don't want the content to be filtered we can use the character "-
" (minus).
To use a Jade template, we compile it using jade.compile
. This results with a template
function. If we pass an object to this function, we're going to get a rendered HTML as the result. We display the HTML inside the #greeting
element.
3.139.105.159