Pug에서 JSON을 반복하려고하지만 길이 오류가 계속 발생합니다.
나는 express와 pug를 사용하고 있습니다.
다음은 index.js 파일입니다.
app.get('/', function(req, res) {
var bookStore = [
{
title: "Templating with Pug",
author: "Winston Smith",
pages: 143,
year: 2017
},
{
title: "Node.js will help",
author: "Guy Fake",
pages: 879,
year: 2015
}
];
res.render("index", {
bookStore: bookStore
});
});
다음은 pug 템플릿입니다.
each book in bookStore
ul
li= book.title
li= book.author
li= book.pages
li= book.year
pug cli를 사용하여 index.pug 파일을 번역하려고 할 때마다 다음 오류가 발생합니다.
TypeError: index.pug:1
> 1| each book in bookStore
2| ul
3| li= book.title
4| li= book.author
Cannot read property 'length' of undefined
at eval (eval at wrap (C:\Users\\AppData\Roaming\npm\node_modules\pug-cli\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:6:32)
at eval (eval at wrap (C:\Users\\AppData\Roaming\npm\node_modules\pug-cli\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:53:4)
at template (eval at wrap (C:\Users\\AppData\Roaming\npm\node_modules\pug-cli\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:54:3)
at renderFile (C:\Users\\AppData\Roaming\npm\node_modules\pug-cli\index.js:285:40)
at C:\Users\\AppData\Roaming\npm\node_modules\pug-cli\index.js:149:5
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\\AppData\Roaming\npm\node_modules\pug-cli\index.js:148:9)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32) {
path: 'index.pug'
}
처음에는 내 코드에 대해 확신이 없었습니다. 그러나 이것은 아마도 작동하는 예입니다.https://pug.programmingpedia.net/en/tutorial/9545/iteration-with-pug
내가 뭘 잘못하고 있는지, pug cli가 bookStore 변수를 "알지"못하기 때문에 컴파일되지 않는 것 같습니다. 그러나 그것이 템플릿의 원칙이 아닙니까? 선언이나 뭔가를 놓쳤습니까?
답변
cli 대신 pug 시작하기에서 언급 한 작업을 수행하려면 express를 사용해야 합니다.
먼저 npm install express pug
패키지를 설치하기 위해 실행하십시오 .
둘째, 다음 코드로 server.js를 설정하십시오.
// server.js
const express = require('express')
const app = express()
// setup template you want to use.
app.set("view engine", "pug")
app.get('/', function (req, res) {
res.render('index', {test: [1,2,3]})
})
app.listen(8080)
셋째, 다음 내용으로 index.pug를 "views / index.pug"로 설정합니다.
div
each val in test
ul
li= val
이제 폴더 구조는 다음과 같습니다.
|-- node_modules
|-- server.js
|-- views
|----|---index.pug
넷째, node server.js
.
마지막 http://localhost:8080
으로 브라우저에 url을 입력 하면 결과가 표시됩니다.
나는 그것을 알아 냈습니다 : 배열로 .pug 파일을 컴파일 할 때 -O 옵션을 사용하여 일부 변수를 지정해야합니다 : pug -O '{"bookStore": "test"}' index.pug
작동하지만 : 작동 pug index.pug
하지 않습니다.
제 생각 엔 좀 이상 해요.