프로그래밍/Node.js

Node.js 생활코딩 정리 – 웹 앱제작 글목록 만들기

가카리 2016. 11. 27. 15:25
반응형

웹앱 제작4 : 글 목록 만들기

 

jade template 엔진에서 Iteration 사용법을 알아야 글목록을 출력 할 수 있다.

 

 

app_file.js에서 추가한 내용

 

//글목록을 표시

app.get('/topic', function(req, res){

fs.readdir('data', function(err, files){//첫번째는 에러 두번째는 파일목록을 전송받음

if(err){//에러가 있다면 여기서 처리

res.status(500).send('Internal Server Error');

}

res.render('view', {topics:files});//템플릿 사용 topics라는 이름으로 files 넘김

});

});

 

 

여기서 topics라는 이름으로 files를 넘겨준다. files는 다음 data 디렉터리에 있는 파일들의 이름이다.

 

그 후 view.jade 파일을 다음과 같이 구성하면

 

doctype html

html

head

meta(charset='utf-8')

body

h1 server side javascript

ul

each topic in topics

li

a(href='/topic/'+topic)= topic

 

 

출력화면

아래와 같이 게시글목록을 동적으로 만들 수 있다.

 

물론 클릭 시 다음과 같이 /topic/파일명으로 이동을 하게 된다.

 

 

 

출처 : https://opentutorials.org/course/2136

 

반응형