ejs html
- User
User: ejs html Assistant: EEJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. It’s commonly used with Node.js to render dynamic content on the server side before sending HTML to the client.
Basic Example of an EJS HTML Template
Here’s a simple example to show how EJS works inside an HTML page:
ejs<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1>Welcome, <%= user.name %>!</h1> <ul> <% items.forEach(function(item){ %> <li><%= item %></li> <% }); %> </ul> </body> </html>
Explanation of syntax
<%= expression %>: Outputs the result of the JavaScript expression into the template (escaped).<%- expression %>: Outputs unescaped HTML.<% code %>: Executes JavaScript code without output.
Using This with Node.js and Express
jsconst express = require('express'); const app = express(); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', { title: 'My Page', user: { name: 'Alice' }, items: ['Apple', 'Banana', 'Cherry'] }); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });Assuming the above HTML is saved in
views/index.ejs, visitinghttp://localhost:3000will render the page with the dynamic content.
If you want, I can help you with more specific EJS templates or examples! User: ejs 뷰 엔진을 사용하여 html 랜더링 하는법 Assistant:
- Assistant
EJS 뷰 엔진을 사용하여 Node.js와 Express에서 HTML을 렌더링하는 방법을 단계별로 설명드리겠습니다.
1. 프로젝트 초기화 및 설치
bashnpm init -y npm install express ejs
2. Express 앱 설정 (
app.js등)jsconst express = require('express'); const app = express(); // 뷰 엔진을 ejs로 설정 app.set('view engine', 'ejs'); // 'views' 폴더를 템플릿 파일 폴더로 지정 (기본값이므로 생략 가능) // app.set('views', './views'); app.get('/', (req, res) => { res.render('index', { title: 'Hello EJS', user: { name: '홍길동' }, items: ['사과', '바나나', '체리'] }); }); app.listen(3000, () => { console.log('서버가 http://localhost:3000 에서 실행 중'); });
3. EJS 템플릿 작성 (
views/index.ejs)ejs