【问题标题】:Iterate over javascript object in pug迭代 pug 中的 javascript 对象
【发布时间】:2018-09-23 20:29:46
【问题描述】:

我已经看到了其中一些问题,但答案似乎从来都不是明确的。我需要在我的哈巴狗视图中遍历一个 javascript 对象。第一次使用哈巴狗,所以我可能会遗漏一些明显的东西。

控制器:

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

这是创建对象的实际函数:

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
    });
}

现在,剩下的就是迭代我认为的对象。我不断收到可怕的Cannot read property 'length' of undefined。 Console.log 显示控制器显示正确的数据。

[{ 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.' }]

(对象比较多,只是举个例子)

我的观点是这样的:

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

【问题讨论】:

    标签: javascript node.js loops express pug


    【解决方案1】:

    您的问题在于渲染功能,只需进行一些小改动即可轻松解决。

    而不是这个:

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

    你应该这样做:

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

    console.log 没有a specified return type,所以你应该只将它用作日志写入器,而不是依赖它返回任何内容。将日志条目单独保存在单独的行中。

    注意单词集合是如何包含在以“单词”为键的对象中的。这为 pug 模板正确设置它以使用变量名称 words 引用它。

    您在模板中设置的每个循环看起来不错,并且在您进行上述更改后应该可以工作。

    为了更进一步,假设您还想在模板中添加“今日词汇”。渲染函数如下所示:

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

    您的模板可能如下所示:

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

    【讨论】:

    • 感谢老哥的有见地的回答!当我回到我的电脑时,我会添加你的更改。
    猜你喜欢
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2016-05-30
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    相关资源
    最近更新 更多