8

So I am using a javascript object to render a list of items. My object looks like this:

{
            text: 'One',
            url: 'index.pug'
        },
        {
            text: 'Two',
            url: 'Two.pug'
        },
        {
            text: 'Three',
            url: 'Three.pug'
        }
}

The interesting part is when pug renders them. I am rendering them using something like this:

div
    ul.horizontalScroll
        each item in params.apps
            li
                a(onclick="loadXMLDoc(#{item.url})") #{item.text}

What I cannot figure out is why item.text renders correctly, but on click the link doesn't ping the function. In chrome inspector, I saw this:<a onclick="loadXMLDoc(#)">One </a>. Why is the argument not coming through as index.pug like it should??

perennial_
  • 1,798
  • 2
  • 26
  • 41
  • Did you try to use single quote instead of double quote? Let change `onclick="loadXMLDoc(#{item.url})"` should be `onclick='loadXMLDoc(#{item.url})'` – Huy Nguyen Jul 01 '16 at 16:09
  • Single quotes give me an `Uncaught SyntaxError: Invalid or unexpected token` – perennial_ Jul 01 '16 at 16:11
  • Possible duplicate of [Put Jade local variable in tag attribute](http://stackoverflow.com/questions/5081534/put-jade-local-variable-in-tag-attribute) – Seth Jul 01 '16 at 16:31

2 Answers2

4

Try concatenating the variable within the attribute:

a(onclick="loadXMLDoc('" + item.url + "')") #{item.text}
Seth
  • 10,198
  • 10
  • 45
  • 68
  • Perfect! (for my purposes, I had to add single quotes around item.url, but your solution answered the problem). I have no idea why I didn't think of this already. `a(onclick="dostuff(" + "'" + item.url + "'" + ")") #{item.text} ` – perennial_ Jul 01 '16 at 16:31
  • :) glad it helped. I've updated the answer. You can avoid the redundant concatenation that you're doing by moving the single quotes into the first and last strings. – Seth Jul 01 '16 at 16:32
0

The accepted solution did not work for me. I was able to move on with something slightly different.

a(onclick="loadXMLDoc('#{item.url}')") #{item.text}

Note the difference in single and double quotes. Also watch out, because text autocomplete might try to add even more quotes.

This solution works because loadXMLDoc expects a string. You need to use different quote chars so that the url string becomes nested inside of the attribute string when it is converted to html.

furt furt
  • 121
  • 1
  • 8