Skip to content
This repository
Browse code

Merge branch 'feature/attr-interpolation'

  • Loading branch information...
commit 449b4f2439580371a57fce4315502e402d1fdf53 2 parents ae54aaa + 4523a6d
TJ Holowaychuk authored

Showing 3 changed files with 29 additions and 1 deletion. Show diff stats Hide diff stats

  1. +11 0 Readme.md
  2. +7 1 lib/lexer.js
  3. +11 0 test/jade.test.js
11 Readme.md
Source Rendered
@@ -10,6 +10,7 @@
10 10 - great readability
11 11 - flexible indentation
12 12 - block-expansion
  13 + - attribute interpolation
13 14 - code is escaped by default for security
14 15 - contextual error reporting at compile & run time
15 16 - executable for compiling jade templates via the command line
@@ -321,6 +322,16 @@ Colons work:
321 322
322 323 rss(xmlns:atom="atom")
323 324
  325 +Suppose we have the `user` local `{ id: 12, name: 'tobi' }`
  326 +and we wish to create an anchor tag with `href` pointing to "/user/12"
  327 +we could use regular javascript concatenation:
  328 +
  329 + a(href='/user/' + user.id)= user.name
  330 +
  331 +or we could use jade's interpolation:
  332 +
  333 + a(href='/user/#{user.id}')= user.name
  334 +
324 335 ### Doctypes
325 336
326 337 To add a doctype simply use `!!!` followed by an optional value:
8 lib/lexer.js
@@ -298,6 +298,12 @@ Lexer.prototype = {
298 298 return states[states.length - 1];
299 299 }
300 300
  301 + function interpolate(attr) {
  302 + return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
  303 + return "' + (" + expr + ") + '";
  304 + });
  305 + }
  306 +
301 307 this.consume(index + 1);
302 308 tok.attrs = {};
303 309
@@ -319,7 +325,7 @@ Lexer.prototype = {
319 325 if ('' == key) return;
320 326 tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
321 327 ? true
322   - : val;
  328 + : interpolate(val);
323 329 key = val = '';
324 330 }
325 331 break;
11 test/jade.test.js
@@ -445,6 +445,17 @@ module.exports = {
445 445 assert.equal('<meta content="what\'s up? \'weee\'"/>', render('meta(content="what\'s up? \'weee\'")'));
446 446 },
447 447
  448 + 'test attr interpolation': function(assert){
  449 + assert.equal('<a href="/user/12">tj</a>'
  450 + , render("a(href='/user/#{id}') #{name}", { locals: { name: 'tj', id: 12 }}));
  451 +
  452 + assert.equal('<a href="/user/12-tj">tj</a>'
  453 + , render("a(href='/user/#{id}-#{name}') #{name}", { locals: { name: 'tj', id: 12 }}));
  454 +
  455 + assert.equal('<a href="/user/&lt;script&gt;">tj</a>'
  456 + , render("a(href='/user/#{id}') #{name}", { locals: { name: 'tj', id: '<script>' }}));
  457 + },
  458 +
448 459 'test attr parens': function(assert){
449 460 assert.equal('<p foo="bar">baz</p>', render('p(foo=((("bar"))))= ((("baz")))'));
450 461 },

0 comments on commit 449b4f2

Please sign in to comment.
Something went wrong with that request. Please try again.