Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating values in HTML attributes - Pug (Jade)

I am trying to construct an anchor tag with a dynamic href attribute in Jade.

I did go through the docs and some SO questions but they didn't help me. This is what I tried.

a(href= "http://www.imdb.com/title/#{movie.imdb_id}") Know more

But it renders

http://www.imdb.com/title/#{movie.imdb_id}  

rather than

http://www.imdb.com/title/tt1234567

However this works

a(href= "http://www.imdb.com/title/" + movie.imdb_id) Know more

and this too.

- var url = "http://www.imdb.com/title/" + movie.imdb_id;
  a(href= url) Know more

What's wrong with the first version?

like image 456
Arun Kumar Mohan Avatar asked Aug 11 '16 02:08

Arun Kumar Mohan


2 Answers

Interpolation is only available in text.

You need to use JS string concatenation for attributes:

a(href="http://www.imdb.com/title/" + movie.imdb_id) Know more

If you JavaScript runtime supports ES2015 template string, you can also use them (notice the backticks):

a(href=`http://www.imdb.com/title/${movie.imdb_id}`) Know more

Reference

like image 172
Iso Avatar answered Oct 29 '22 17:10

Iso


the pug variable declaration doesnt work in this case using #{...} the right syntax goes this way,

a(attributes) Know more

a(href="http://www.imdb.com/title/"+ movie.imdb_id) Know more

the attributes is an expression so it renders correcly, or you could use ES5 template literals with back quotes to render the variable along side the text which becomes

a(href=`http://www.imdb.com/title/${movie.imdb_id}`) Know more

note that when using back quotes with template literals your variable expression are enclosed in parenthesis and a leading $ sign, that is ${..expression..}

like image 38
Ande Caleb Avatar answered Oct 29 '22 17:10

Ande Caleb