taenyLog
NodeJS | 템플레이팅으로 동적 HTML 구성 본문
템플레이팅
특정 로직과 HTML 응답 생성을 결합
EJS (Embedded JavaScript) - Node.js에서 많이 사용하는 템플릿엔진
EJS용 Express 구성하기
http://expressjs.com/en/5x/api.html#app.set
Express 5.x - API Reference
Express 5.x API Note: This is early beta documentation that may be incomplete and is still under development. express() Creates an Express application. The express() function is a top-level function exported by the express module. const express = require('
expressjs.com
app.set(name,value)
Assigns setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table.
Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo'). Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').
Retrieve the value of a setting with app.get().
app.set('title', 'My Site')
app.get('title') // "My Site"
+)
[nodemon] app crashed - waiting for file changes before starting...
오타로 인한 오류였음 ..
뷰디렉토리 설정하기
Express에서 찾는 어플리케이션을 view폴더가 있는 디렉토리와 동일한 곳에서 열었을때만 작동한다
현재의 폴더에서는 nodemon index.js 명령시 잘 작동하지만
한 단계 상위폴더로 가면 index.js가 안보일것이다 .여기서 nodemon dir이름/index.js 해도 실행잘됨
하지만 localhost:8080 에서는 오류가 뜬다.
해결 방법 : 다른 경로에서도 잘 작동하게..
const express = require('express');
const app = express();
const path = require('path')
app.set('view engine','ejs');
app.set('views', path.join(__dirname,'/views'));
app.get('/',(req,res)=>{
res.render('home') //home.ejs로 이동
})
app.listen(8080, () => {
console.log("Listen On Port 8080")
})
const path = ~
app.set('views', path.join(__dirname, 'views'));
추가해준다.
내장된 노드에 있는 path라는 모듈은 파일과 디렉토리 경로에 관한 메서드 제공
EJS 구문
EJS 같은 템플레이팅 엔진을 사용하는 이유는 로직을 더하고 데이터를 보충하기위해서.
EJS -- Embedded JavaScript templates
Simple syntax JavaScript code in simple, straightforward scriptlet tags. Just write JavaScript that emits the HTML you want, and get the job done!
ejs.co
Tags
- <% 'Scriptlet' tag, for control-flow, no output
- <%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
- <%= Outputs the value into the template (HTML escaped)
- <%- Outputs the unescaped value into the template
- <%# Comment tag, no execution, no output
- <%% Outputs a literal '<%'
- %> Plain ending tag
- -%> Trim-mode ('newline slurp') tag, trims following newline
- _%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
Tag를 사용한 예시
위와 같이 그저 자바스크립트 코드이다.
EJS에서 값이 HTML의 결과에 포함하기 위해선 JavaScript를 사용하기 위해선 <%= %>을 써주어야한다.
템플릿에 전달
random.ejs에서 변수를 생성해서 웹에 나타나게 가능하다.
하지만 ejs에서 로직을 간단하게 하는 것이 좋다.
index.js에 변수 생성해서 random.ejs에서 쓸 수 있게함.
num 의 변수를 rand 대신 num으로 써도 상관없음
{num : num}
서브레딧 템플릿 데모
변수를 경로에서 직접 가져가서 렌더링 할 필요없이 변수를 가져가 데이터베이스에서 정보를 찾는다.
찾은 데이터를 req.params에 전달한다.
EJS 조건문
<h3>와 같이 간단히 코드 작성 가능
EJS 루프
<ul>
<% for(let cat of cats){ %>
<li><%= cat %></li>
<% } %>
</ul>
주의할 점은 for문에는 <%
렌더링 될 값에는 <%= 을 써주었다.
복잡한 서브레딧 데모
res.render('subreddit',{subreddit}) // 데이터를 객체로 옮김
// 위의 코드 대신 아래의 코드를 사용하여 데이터의 각 특성에 접근 가능 name, subscribers, description 등
/*
"soccer": {
"name": "Soccer",
"subscribers": 800000,
"description": "The football subreddit. News, results and discussion about the beautiful game.",
"posts": [
{
"title": "Marten de Roon to make pizza for more than 1,000 people in Bergamo if Atalanta win the Champions league.",
"author": "joeextreme"
},
{
"title": "Stephan Lichtsteiner has retired from professional football",
"author": "odd person"
},
{
"title": "OFFICIAL: Dani Parejo signs for Villareal.",
"author": "joeextreme"
}
]
}
*/
res.render('subreddit', {...data})
index.js
subreddit.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= name %></title>
</head>
<body>
<h1>Browsing The <%= name %>'s subscribers : <%= subscribers%> </h1>
<p><%= description %></p>
<% for(let post of posts){ %>
<article>
<p><%= post.title%>-<b><%= post.author%></b></p>
<img src ="<%= post.img%>" alt="">
</article>
<% } %>
</body>
</html>
Express의 정적 Assets 사용
https://expressjs.com/en/starter/static-files.html
Serving static files in Express
Serving static files in Express To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The function signature is: express.static(root, [options]) The root argument specifies th
expressjs.com
Express에서 정적 파일 제공
이미지, CSS 파일 및 JavaScript 파일과 같은 정적 파일을 제공하려면 express.staticExpress에 내장된 미들웨어 기능을 사용하십시오.
함수 서명은 다음과 같습니다.
express.static(root, [options])
인수 root는 정적 자산을 제공할 루트 디렉토리를 지정합니다. 인수 에 대한 자세한 내용은 express.static 을options 참조하십시오 .
예를 들어 다음 코드를 사용하여 이름이 지정된 디렉토리에서 이미지, CSS 파일 및 JavaScript 파일을 제공합니다 public.
app.use(express.static('public'))
app.use(express.static(path.join(__dirname,'public')))
위와같은 코드로 바꾸어주어 절대경로로 바꾸어줌
부트스트랩과 Express
부트스트랩 시작
https://getbootstrap.kr/docs/5.2/getting-started/introduction/
Bootstrap 시작하기
Bootstrap은 강력하고 기능이 풍부한 프론트엔드 툴킷입니다. 프로토타입부터 프로덕션까지 뭐든지 빠르게 빌드해보세요.
getbootstrap.kr
부트스트랩 사용시 제이쿼리 관련 오류 해결
>> https://taenylife.tistory.com/64
Bootstrap 사용시 jquery 오류
bootstrap.min.js:6 Uncaught TypeError: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript. at Object.jQueryDetection (bootstrap.min.js:6:2536)
taenylife.tistory.com
EJS와 파일 분할
모든 템플릿을 공통으로 사용할 수 있게하고 하위 템플릿에 그 템플릿을 포함하는 방법
'Web' 카테고리의 다른 글
RESTful 라우트 (0) | 2023.06.24 |
---|---|
Bootstrap 사용시 jquery 오류 (0) | 2023.06.22 |
NodeJs | Express로 서버제작 (0) | 2023.06.21 |
NodeJS | 언어 맞추기 프로젝트 (0) | 2023.06.21 |
NodeJS | process.argv[2]; (0) | 2023.06.21 |