Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added attribute interpolation support

sooooo many people just expect this to work,
so now we have it
  • Loading branch information...
commit 4523a6d4951909f85e8620d534b49df7c3a2e5d7 1 parent ae54aaa
@tj tj authored
Showing with 29 additions and 1 deletion.
  1. +11 −0 Readme.md
  2. +7 −1 lib/lexer.js
  3. +11 −0 test/jade.test.js
View
11 Readme.md
@@ -10,6 +10,7 @@
- great readability
- flexible indentation
- block-expansion
+ - 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
@@ -321,6 +322,16 @@ 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:
+
+ a(href='/user/#{user.id}')= user.name
+
### Doctypes
To add a doctype simply use `!!!` followed by an optional value:
View
8 lib/lexer.js
@@ -298,6 +298,12 @@ Lexer.prototype = {
return states[states.length - 1];
}
+ function interpolate(attr) {
+ return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
+ return "' + (" + expr + ") + '";
+ });
+ }
+
this.consume(index + 1);
tok.attrs = {};
@@ -319,7 +325,7 @@ Lexer.prototype = {
if ('' == key) return;
tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
? true
- : val;
+ : interpolate(val);
key = val = '';
}
break;
View
11 test/jade.test.js
@@ -445,6 +445,17 @@ module.exports = {
assert.equal('<meta content="what\'s up? \'weee\'"/>', render('meta(content="what\'s up? \'weee\'")'));
},
+ 'test attr interpolation': function(assert){
+ assert.equal('<a href="/user/12">tj</a>'
+ , render("a(href='/user/#{id}') #{name}", { locals: { name: 'tj', id: 12 }}));
+
+ assert.equal('<a href="/user/12-tj">tj</a>'
+ , render("a(href='/user/#{id}-#{name}') #{name}", { locals: { name: 'tj', id: 12 }}));
+
+ assert.equal('<a href="/user/&lt;script&gt;">tj</a>'
+ , render("a(href='/user/#{id}') #{name}", { locals: { name: 'tj', id: '<script>' }}));
+ },
+
'test attr parens': function(assert){
assert.equal('<p foo="bar">baz</p>', render('p(foo=((("bar"))))= ((("baz")))'));
},
Please sign in to comment.
Something went wrong with that request. Please try again.