简体   繁体   中英

JavaScript - Pass second argument to ES6 Template whilst using .map

I am using es6 templates but have run into an issue when trying to pass a second argument to another template used internally within the original.

At first I was only using a result.relevantJobTypes argument but now I am trying to also pass the result.id for use within the template but I'm not sure how to do it because of the map .

var resultTemplate = ({ result }) => {
    return `
        ${result.id} 
        ${result.relevantJobTypes.length < 1 ? '' : `
            ${result.relevantJobTypes.map(jobType => jobTypeTemplate({
                jobType // , result.id -> I want to use result.id somehow in jobTypeTemplate
            })).join('')}
        `}
    `;
}

var jobTypeTemplate = ({ jobType }) => {
    // template code
}

Update

Trying to implement @Bergi's answer but the id is undefined within the relevantJobTypes template:

${result.relevantJobTypes.length < 1 ? '' : `
    ${result.relevantJobTypes.map(jobType => jobTypeTemplate({
        jobType
    }, result.id)).join('')}
`}

var jobTypeTemplate = ({ jobType, id }) => {
    // template code
}

#2

Finally got it, I had to update the signature of jobTypeTemplate to be var jobTypeTemplate = ({ jobType }, id) => { rather than jobType, id

It's just a standard function call, this has nothing to do with template literals. Instead of

jobTypeTemplate({
    jobType, result.id // SyntaxError
})

you will need to use

jobTypeTemplate({
    jobType
}, result.id)

for a second argument. Of course you could also put a second property in the object literal:

jobTypeTemplate({
    jobType,
    id: result.id
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM