我见过其中一些问题,但答案似乎从来都不是明确的。我需要在我的哈巴狗 View 中迭代一个 javascript 对象。第一次使用哈巴狗,所以我可能会遗漏一些明显的东西。
Controller :
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
});
}
现在,剩下的就是迭代我 View 中的对象。我不断收到可怕的无法读取未定义的属性“长度”
。 Console.log 显示 Controller 显示正确的数据。
[{ 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
最佳答案
您的问题出在渲染函数中,只需进行一些小的更改即可轻松修复。
而不是这个:
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
关于javascript - 迭代 pug 中的 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470000/