Erik
Erik

Reputation: 14770

How to write javascript block in jade?

I need to write some javascript code in my jade template but don't wrap inside script tag:

body
   container
       p
          - var obj = {
          -    "price": 100,
          -    "qty: 3
          -};

          - var result = obj.price * obj.qty;

          Result is: !{result}.

In the code above I do some computations and output result. All works fine but looks ugly due multiple -. Does jade support some blocks to write javascript without using of multiple -

Upvotes: 0

Views: 871

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

Jade doesn't currently support stringing multiple lines of unbuffered code together. Each - should be followed by a complete statement.

The obj will have to be initialized in one:

p
    - var obj = { price: 100, qty: 3 };

Or set in multiple statements:

p
    - var obj = {};
    - obj.price = 100;
    - obj.qty = 3;

Or, defined as "locals" to render with:

var jade = require('jade');

var html = jade.renderFile(__dirname + '/template.jade', {
    obj: {
        price: 100,
        qty: 3
    }
});
p Result is: #{obj.price * obj.qty).

Also note that the Result ... will need a | prefix to signify it as a line of text when it's on its own line.

p
    | Result is #{result}

Upvotes: 2

Related Questions