Pug `#{}` fails to load variable inside `onclick`
Asked Answered
C

2

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??

Caracaraballo answered 1/7, 2016 at 15:41 Comment(3)
Did you try to use single quote instead of double quote? Let change onclick="loadXMLDoc(#{item.url})" should be onclick='loadXMLDoc(#{item.url})'Cable
Single quotes give me an Uncaught SyntaxError: Invalid or unexpected tokenCaracaraballo
Possible duplicate of Put Jade local variable in tag attributeMaureenmaureene
M
4

Try concatenating the variable within the attribute:

a(onclick="loadXMLDoc('" + item.url + "')") #{item.text}
Maureenmaureene answered 1/7, 2016 at 16:26 Comment(2)
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} Caracaraballo
:) 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.Maureenmaureene
C
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.

Cotidal answered 6/11, 2017 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.