대딩코딩/웹개발 스터디
[Express] 8. View의 확장
시데브
2023. 12. 1. 16:41
.ejs 파일 중복 내용 처리
파일명: main.js
const express = require('express');
const app = express();
const port = 3000;
//app.set - 환경변수 설정
//app.use - 모든 리퀘스트에 대해서 괄호 안의 내용을 적용
//app.get - 경로에 대한 get 방식의 요청에 대한 뒤 함수 처리를 해줌
app.set('view engine', 'ejs');
app.set('views', 'views');
const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
app.set('layout', 'index.ejs'); //기본 layout을 index.ejs로 설정
const homeController = require('./controllers/homeController.js');
const topicController = require('./controllers/topicController.js');
app.get('/', homeController.getTopics);
app.get('/topic/read/:topic_id', topicController.viewTopic);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
파일명: index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="/"><h1>WEB</h1></a>
<ol>
<% for(let topic of topics) { %>
<li><a href="/topic/read/<%= topic.topic_id %>"><%= topic.title %></a></li>
<% } %>
</ol>
<a href="/post/create">create</a>
<%- body %>
</body>
</html>
>> %- body% 부분에 새로 추가되는 내용이 들어감
파일명: topic.ejs
<h1><%= topic.title %></h1>
<p><%= topic.content %></p>
파일명: home.ejs
<h1>Welcome!</h1>
>> home은 따로 처리해줘야함
>> body 자리에 index.ejs를 넣으면 index.ejs 안에 또 index.ejs를 넣는 현상 발생
파일명: homeController.js
const homeModel = require('../models/homeModel.js');
module.exports = {
getTopics: async (req, res) => {
const topics = await homeModel.home();
res.render('home.ejs', {topics: topics});
}
}
728x90
반응형