Interploating values in HTML attributes - Pug(Jade)

自作多情 提交于 2019-12-10 20:23:43

问题


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

I did go through http://jade-lang.com/reference/interpolation/ and some SO questions but 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?


回答1:


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




回答2:


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




回答3:


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!"




回答4:


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



来源:https://stackoverflow.com/questions/38886286/interploating-values-in-html-attributes-pugjade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!