Interpolating values in HTML attributes - Pug (Jade)
Asked Answered
A

4

10

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?

Antonomasia answered 11/8, 2016 at 2:17 Comment(0)
L
17

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

Laborer answered 11/8, 2016 at 11:38 Comment(0)
H
3

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..}

Helvetia answered 28/4, 2019 at 11:31 Comment(0)
H
0

When you quote it simply tells pug "this is a string". That's basic JS. Interpolation works with #{'#{interpolation}'} too! is an example which renders "Interpolation works with #{interpolation} too!"

Herbalist answered 24/12, 2016 at 21:7 Comment(1)
Look through the examples on pugjs.org/language/interpolation.htmlHerbalist
G
-3

I don't have any knowledge about pug(jade)

But my guess is "a(your code)" is already a signal to pug(jade) that it is in the controller's scope already.. and "{variable}" is also an indicator that you are accessing controller's scope. so

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

for "{}" inside a() is no longer an indicator that your are trying to access controller's scope because you're already in the controller's scope.. so "{}" inside a() is just a string, {movie.imdb_id} is part of the link string.

So in order for the framework to identity that movie.imdb_id is a variable, you should separate it from the actual string.

NOTE: This is just a guess..I'm using angular

Graniteware answered 11/8, 2016 at 3:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.