Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for node. For discussion join the Google Group.
Jade version 0.31.0 deprecated implicit text only support for scripts and styles. To fix this all you need to do is add a . character after the script or style tag.
It is hoped that this change will make jade easier for newcommers to learn without affecting the power of the language or leading to excessive verboseness.
If you have a lot of jade files that need fixing you can use fix-jade to attempt to automate the process.
You can test drive Jade online here.
- Features
- Implementations
- Installation
- Browser Support
- Public API
- Syntax
- Filters
- Code
- Iteration
- Conditionals
- Template inheritance
- Block append / prepend
- Includes
- Mixins
- Generated Output
- Example Makefile
- jade(1)
- Tutorials
- License
- client-side support
- great readability
- flexible indentation
- block-expansion
- mixins
- static includes
- attribute interpolation
- code is escaped by default for security
- contextual error reporting at compile & run time
- executable for compiling jade templates via the command line
- html 5 mode (the default doctype)
- optional memory caching
- combine dynamic and static tag classes
- parse tree manipulation via filters
- template inheritance
- block append / prepend
- supports Express JS out of the box
- transparent iteration over objects, arrays, and even non-enumerables via
each - block comments
- no tag prefix
- filters
- :stylus must have stylus installed
- :less must have less.js installed
- :markdown must have markdown-js, node-discount, or marked installed
- :cdata
- :coffeescript must have coffee-script installed
- Emacs Mode
- Vim Syntax
- TextMate Bundle
- Coda/SubEtha syntax Mode
- Screencasts
- html2jade converter
Hello ' + escape((interp = name) == null ? '' : interp) + '\n
'); } return buf.join(""); } Through the use of Jade's ./runtime.js you may utilize these pre-compiled templates on the client-side without Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as jade.attrs, jade.escape etc. To enable this you should pass { client: true } to jade.compile() to tell Jade to reference the helper functions via jade.attrs, jade.escape etc. function anonymous(locals, attrs, escape, rethrow) { var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow; var buf = []; with (locals || {}) { var interp; buf.push('\nHello ' + escape((interp = name) == null ? '' : interp) + '\n
'); } return buf.join(""); }## Public API var jade = require('jade'); // Compile a function var fn = jade.compile('string of jade', options); fn(locals);selfUse aselfnamespace to hold the locals (false by default)localsLocal variable objectfilenameUsed in exceptions, and required when using includesdebugOutputs tokens and function body generatedcompilerCompiler to replace jade's defaultcompileDebugWhenfalseno debug instrumentation is compiledprettyAdd pretty-indentation whitespace to output (false by default)
wahoo!
. well cool, but how about large bodies of text: p | foo bar baz | rawr rawr | super cool | go jade go rendersfoo bar baz rawr.....
interpolation? yup! both types of text can utilize interpolation, if we passed { name: 'tj', email: '[email protected]' } to the compiled function we can do the following: #user #{name} <#{email}> outputs#{something}
We can also utilize the unescaped variant !{html}, so the following will result in a literal script tag: - var html = "" | !{html} Nested tags that also contain text can optionally use a text block: label | Username: input(name='user[name]') or immediate tag text: label Username: input(name='user[name]') As an alternative, we may use a trailing . to indicate a text block, for example: p. foo asdf asdf asdfasdfaf asdf asd. outputs:foo asdf asdf asdfasdfaf asdf asd.
This however differs from a trailing . followed by a space, which although is ignored by the Jade parser, tells Jade that this period is a literal: p . outputs:.
It should be noted that text blocks should be doubled escaped. For example if you desire the following output.foo\bar
use: p. foo\\bar### Comments Single line comments currently look the same as JavaScript comments, aka // and must be placed on their own line: // just some paragraphs p foo p bar would outputfoo
bar
Jade also supports unbuffered comments, by simply adding a hyphen: //- will not output within markup p foo p bar outputtingfoo
bar
### Block Comments A block comment is legal as well: body // #content h1 Example outputting Jade supports conditional-comments as well, for example: head //if lt IE 8 script(src='/ie-sucks.js') outputs: ### Nesting Jade supports nesting to define the tags in a natural way: ul li.first a(href='#') foo li a(href='#') bar li.last a(href='#') baz### Block Expansion Block expansion allows you to create terse single-line nested tags, the following example is equivalent to the nesting example above. ul li.first: a(href='#') foo li: a(href='#') bar li.last: a(href='#') baz### Case The case statement takes the following form: html body friends = 10 case friends when 0 p you have no friends when 1 p you have a friend default p you have #{friends} friends Block expansion may also be used: friends = 5 html body case friends when 0: p you have no friends when 1: p you have a friend default: p you have #{friends} friends### Attributes Jade currently supports ( and ) as attribute delimiters. a(href='/login', title='View login page') Login When a value is undefined or null the attribute is not added, so this is fine, it will not compile something="null". div(something=null) Boolean attributes are also supported: input(type="checkbox", checked) Boolean attributes with code will only output the attribute when true: input(type="checkbox", checked=someValue) Multiple lines work too: input(type='checkbox', name='agreement', checked) Multiple lines without the comma work fine: input(type='checkbox' name='agreement' checked) Funky whitespace? fine: input( type='checkbox' name='agreement' checked) Colons work: rss(xmlns:atom="atom") Suppose we have the user local { id: 12, name: 'tobi' } and we wish to create an anchor tag with href pointing to "/user/12" we could use regular javascript concatenation: a(href='/user/' + user.id)= user.name or we could use jade's interpolation, which I added because everyone using Ruby or CoffeeScript seems to think this is legal js..: a(href='/user/#{user.id}')= user.name The class attribute is special-cased when an array is given, allowing you to pass an array such as bodyClasses = ['user', 'authenticated'] directly: body(class=bodyClasses)### HTML Inline html is fine, we can use the pipe syntax to write arbitrary text, in this case some html: html body |Title
|foo bar baz
Or we can use the trailing . to indicate to Jade that we only want text in this block, allowing us to omit the pipes: html body.Title
foo bar baz
Both of these examples yield the same result:Title
foo bar baz
The same rule applies for anywhere you can have text in jade, raw html is fine: html body h1 User #{name}### Doctypes To add a doctype simply use !!!, or doctype followed by an optional value: !!! or doctype Will output the html 5 doctype, however: !!! transitional Will output the transitional doctype. Doctypes are case-insensitive, so the following are equivalent: doctype Basic doctype basic it's also possible to simply pass a doctype literal: doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" yielding: Below are the doctypes defined by default, which can easily be extended: var doctypes = exports.doctypes = { '5': '', 'default': '', 'xml': '', 'transitional': '', 'strict': '', 'frameset': '', '1.1': '', 'basic': '', 'mobile': '' }; To alter the default simply change: jade.doctypes.default = 'whatever you want';## Filters Filters are prefixed with :, for example :markdown and pass the following block of text to an arbitrary function for processing. View the features at the top of this document for available filters. body :markdown Woah! jade _and_ markdown, very **cool** we can even link to [stuff](http://google.com) Renders:Woah! jade and markdown, very cool we can even link to stuff
## Code Jade currently supports three classifications of executable code. The first is prefixed by -, and is not buffered: - var foo = 'bar'; This can be used for conditionals, or iteration: - for (var key in obj) p= obj[key] Due to Jade's buffering techniques the following is valid as well: - if (foo) ul li yay li foo li worked - else p oh no! didnt work Hell, even verbose iteration: - if (items.length) ul - items.forEach(function(item){ li= item - }) Anything you want! Next up we have escaped buffered code, which is used to buffer a return value, which is prefixed by =: - var foo = 'bar' = foo h1= foo Which outputs barbar
. Code buffered by = is escaped by default for security, however to output unescaped return values you may use !=: p!= aVarContainingMoreHTML Jade also has designer-friendly variants, making the literal JavaScript more expressive and declarative. For example the following assignments are equivalent, and the expression is still regular javascript: - var foo = 'foo ' + 'bar' foo = 'foo ' + 'bar' Likewise Jade has first-class if, else if, else, until, while, unless among others, however you must remember that the expressions are still regular javascript: if foo == 'bar' ul li yay li foo li worked else p oh no! didnt work## Iteration Along with vanilla JavaScript Jade also supports a subset of constructs that allow you to create more designer-friendly templates, one of these constructs is each, taking the form: each VAL[, KEY] in OBJ An example iterating over an array: - var items = ["one", "two", "three"] each item in items li= item outputs:My Site
Welcome to my super lame site.
As mentioned include can be used to include other content
such as html or css. By providing an extension, Jade will
read that file in, apply any filter matching the file's
extension, and insert that content into the output.
html head //- css and js have simple filters that wrap them in <style> and <script> tags, respectively include stylesheet.css include script.js body //- "markdown" files will use the "markdown" filter to convert Markdown to HTML include introduction.markdown //- html files have no filter and are included verbatim include content.html
Include directives may also accept a block, in which case the
the given block will be appended to the last block defined
in the file. For example if head.jade contains:
head script(src='/jquery.js')
We may append values by providing a block to include head
as shown below, adding the two scripts.
html include head script(src='/foo.js') script(src='/bar.js') body h1 test
You may also yield within an included template, allowing you to explicitly mark where the block given to include will be placed. Suppose for example you wish to prepend scripts rather than append, you might do the following:
head yield script(src='/jquery.js') script(src='/jquery.ui.js')
Since included Jade is parsed and literally merges the AST, lexically scoped variables function as if the included Jade was written right in the same file. This means include may be used as sort of partial, for example suppose we have user.jade which utilizes a user variable.
h1= user.name p= user.occupation
We could then simply include user while iterating users, and since the user variable is already defined within the loop the included template will have access to it.
users = [{ name: 'Tobi', occupation: 'Ferret' }] each user in users .user include user
yielding:
<div class="user"> <h1>Tobi</h1> <p>Ferret</p> </div>
If we wanted to expose a different variable name as user since user.jade references that name, we could simply define a new variable as shown here with user = person:
each person in users .user user = person include user
tj
- tobi
- loki
- jane
- manny
'); buf.push('' + escape((interp = title) == null ? '' : interp) + ''); buf.push(''); __.lineno = 3; buf.push('
'); buf.push('Just an example'); buf.push('
'); } return buf.join(""); } catch (err) { rethrow(err, __.input, __.filename, __.lineno); } } When the compileDebug option is explicitly false, this instrumentation is stripped, which is very helpful for light-weight client-side templates. Combining Jade's options with the ./runtime.js file in this repo allows you to toString() compiled templates and avoid running the entire Jade library on the client, increasing performance, and decreasing the amount of JavaScript required. function anonymous(locals) { var attrs = jade.attrs, escape = jade.escape; var buf = []; with (locals || {}) { var interp; var title = 'yay' buf.push(''); buf.push('' + escape((interp = title) == null ? '' : interp) + ''); buf.push(''); buf.push('
'); buf.push('Just an example'); buf.push('
'); } return buf.join(""); }## Example Makefile Below is an example Makefile used to compile pages/*.jade into pages/*.html files by simply executing make. Note: If you try to run this snippet and make throws a missing separator error, you should make sure all indented lines use a tab for indentation instead of spaces. (For whatever reason, GitHub renders this code snippet with 4-space indentation although the actual README file uses tabs in this snippet.) JADE = $(shell find . -wholename './pages/*.jade') HTML = $(JADE:.jade=.html) all: $(HTML) %.html: %.jade jade < $< --path $< > $@ clean: rm -f $(HTML) .PHONY: clean this can be combined with the watch(1) command to produce a watcher-like behaviour: $ watch make or you use the watch option below:## jade(1) Usage: jade [options] [dir|file ...] Options: -h, --help output usage information -V, --version output the version number -O, --obj- cssdeck interactive Jade syntax tutorial
- cssdeck interactive Jade logic tutorial
- in Japanese
Copyright (c) 2009-2010 TJ Holowaychuk <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.