Iterate over javascript object in pug

淺唱寂寞╮ 提交于 2021-02-08 02:12:35

问题


I've seen a few of these questions but the answers never seem to be clear cut. I need to iterate through a javascript object in my pug view. First time using pug, so I may be missing something obvious.

Controller:

app.get('/search/:keyword', (req, res) => {
        scraper
        .searchDictionary(req.params.keyword)
        .then(words => {
        res.render('result', console.log(words))
    });
})

Here is the actual function that makes the object:

function searchDictionary(searchTerm){
    const url = `https://www.dictionary.com/browse/${searchTerm}?s=t`
    return fetch(`${url}${searchTerm}`)
        .then(response => response.text())
        .then(body => {
        const words = []
        const $ = cheerio.load(body);
        $('ol').each(function(i, element){
            const $element = $(element)
            const $definition = $(element).find('li')
            const word = {
                keyword: searchTerm,
                definition: $definition.text(),
                speechParts: $('span.luna-pos').text(),
                tenses: $('span.luna-inflected-form').text()
            }
            words.push(word);
        });
        return words
    });
}

Now, all that is left is iterate over the object in my view. I keep getting the dreaded Cannot read property 'length' of undefined. Console.log shows the controller displaying the right data.

[{ keyword: 'cat',
    definition: 'a person, especially a man.a devotee of jazz.',
    speechParts: 'nounverb (used with object),verb (used without object),Verb PhrasesIdioms',
    tenses: 'cat·ted,cat·ting.cat·ted,cat·ting.' }]

(there are more objects, just wanted to show an example)

My view looks like this:

body
h1
    ul
        each word in words
            li= word.keyword

回答1:


Your issues are in the render function, easily fixed with a few small changes.

Instead of this:

res.render('result', console.log(words))

You should do this:

console.log(words);
res.render('result', {"words": words});

console.log doesn't have a specified return type so you should only use it as a log writer and not depend on it returning anything. Keep log entries on their own separate lines.

Note how the words collection is contained inside an object with "words" as the key. This sets it up properly for the pug template to reference it using the variable name words.

The each loop you set up in the template looks good and should work once you make the changes above.

To take this one step further, let's say you also wanted to add a "word of the day" to your template. The render function would look like this:

res.render('result', {
  "words": words,
  "wordOfTheDay": "lorem"
});

Your template could then look like this:

h1 Word Of The Day
p= wordOfTheDay
br
h1 Word List
ul
  each word in words
    li= word.keyword


来源:https://stackoverflow.com/questions/52470000/iterate-over-javascript-object-in-pug

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