지구정복

[Node.js] 02/26 | jade 사용하기(개념, 설치및사용(변수사용, 조건문, each문, while문, 이미지파일 불러오기, 구구단만들기)) 본문

데이터 엔지니어링 정복/HTML-CSS-JavaScript-Spring-Node.js

[Node.js] 02/26 | jade 사용하기(개념, 설치및사용(변수사용, 조건문, each문, while문, 이미지파일 불러오기, 구구단만들기))

eeaarrtthh 2021. 2. 26. 17:42
728x90
반응형
SMALL

복습 및 배울내용

node.js
	웹사이트 구현
	서버구현
		express
			미들웨어
				내부
				외부
					템플릿 처리

* 템플릿 처리 + express-generator(사이트의 frame을 구성) 같이 사용
ejs라이브러리 

	=> login 기능구현가능
		-session
		-cookie
			cookie-parser 사용
pug( = jade)

 

1. pug (= Jade) 사용하기

더보기

1. 개념

템플릿 엔진의 하나로써 node.js용으로 만들어진 express에서 사용하는 view 템플릿 엔진이다.
파일 확장자는 .jade이다.
jade 문법에 맞게 작성하면 해당 내용을 html이나 자바스크립트 언어로 바꿔준다.
jade 문법에서 html을 작성할 때는 태그( <> )가 필요없다.

사용하는 문법은 다음과 같다.

#{ Value } : 데이터 출력 ( html태그 해석 x )
!{ Value } : 데이터 출력 ( html태그 해석 o )

2. 설치 및 사용

먼저 설치부터 한다.

[master@localhost ~]$ su - root
암호:
[root@localhost ~]# npm install -g npm@7.6.0
[root@localhost ~]# exit

[master@localhost ~]$ mkdir jade1
[master@localhost ~]$ cd jade1/
[master@localhost jade1]$ npm init -y

[master@localhost jade1]$ npm install express
[master@localhost jade1]$ npm install jade
[master@localhost jade1]$ code

비주얼 스튜디오 코드에서 jade1 패키지를 연다.
그리고 먼저 server.js를 설정해서 서버를 만들어준다.
-server.js

"use strict"
const express = require( 'express' );
const app = express();

//jade engine을 사용한다는 설정
app.set( 'views', __dirname + '/views' );   //템플릿이 있는 디렉터리 알려주기
app.set( 'view engine', 'jade' );       //사용할 템플릿 view engine한테 알려주기

//static을 이용해서 정적파일 가지고오기
app.use( express.static( './' ) );

app.get( '/', (req, res) => {
    //views에서 hello파일을 가져오라는 의미
    res.render( 'hello' );
})

app.listen( 3000, () => {
    console.log( '3000번 포트에서 서버 대기중입니다.'); 
})

다음으로 views 디렉터리를 만들고 그 안에 hello.jade 파일을 만들어준다.

-hello.jade (이때 공백간격을 스페이스바로 할지 탭으로 할지 정한다음 일정하게 줘야한다.)

doctype
html(lang="ko")
  head
    title Jade Example
    meta( charset="utf-8" )
  body
    h1 Jade - node template engine

pug 언어에 대해서는 아래 사이트 참고한다.
jade-lang.com/

브라우저에서 실행하면 다음과 같다.

 

변수 사용하기

-hello.jade

doctype
html(lang="ko")
  head
    title Jade Example
    meta( charset="utf-8" )
  body
    h1 Jade - node template engine
    - const strVal = 'Hello <strong>World</strong>'
    //- #은 태그를 해석해주지는 않는다.
    div #{ strVal }
    //- ! 태그를 해석해서 html로 만들어준다.
    div !{ strVal } 

 

jade 에서 자바스크립트 조건문사용

-hello.jade

doctype
html(lang="ko")
  head
    title Jade Example
    meta( charset="utf-8" )
  body
    h1 Jade - node template engine
    - const strVal = 'Hello <strong>World</strong>'
    div #{ strVal }
    //- ! 태그를 해석해서 html로 만들어준다.
    div !{ strVal } 

    - const val = true 
    if val
      div val is true 
    else 
      div val is false

 

each문 사용하기

doctype
html(lang="ko")
  head
    title Jade Example
    meta( charset="utf-8" )
  body
    h1 Jade - node template engine
    - const strVal = 'Hello <strong>World</strong>'
    //- #은 태그를 해석해주지는 않는다.
    div #{ strVal }
    //- !은 태그를 해석해서 html로 만들어준다.
    div !{ strVal } 

    - const val = true 
    if val
      div val is true 
    else 
      div val is false

    - const array = [ 'First', 'Second', 'Third' ]
    ul 
      each item, index in array 
        li #{ index } : #{ item }

 

while문 사용하기

doctype
html(lang="ko")
  head
    title Jade Example
    meta( charset="utf-8" )
  body
    h1 Jade - node template engine
    - const strVal = 'Hello <strong>World</strong>'
    //- #은 태그를 해석해주지는 않는다.
    div #{ strVal }
    //- !은 태그를 해석해서 html로 만들어준다.
    div !{ strVal } 

    - const val = true 
    if val
      div val is true 
    else 
      div val is false

    - const array = [ 'First', 'Second', 'Third' ]
    ul 
      each item, index in array 
        li #{ index } : #{ item }
    - let i = 0
    ul 
      while i<4
        li item #{ i++ }

 

이미지 파일 불러오기

새로운 패키지를 만든다.

[master@localhost jade1]$ cd
[master@localhost ~]$ mkdir jade2
[master@localhost ~]$ cd jade2
[master@localhost jade2]$ npm init -y
[master@localhost jade2]$ npm install express
[master@localhost jade2]$ npm install jade

비주얼스튜디오코드에서 jade2 패키지를 연다. 그리고 views라는 디렉터리를 만든다.
그리고 서버를 만들어준다.
-server.js

"use strict"
const express = require( 'express' );
const app = express();

app.set( 'views', __dirname + '/views' );  
app.set( 'view engine', 'jade' );       

app.use( express.static( './' ) );

app.get( '/', (req, res) => {
    const datas = [
        { title: 'cat1', image: 'cat1.png' },
        { title: 'cat2', image: 'cat2.png' },
        { title: 'cat3', image: 'cat3.png' }
    ];

    res.render( 'cats', { title: 'Cats', cats: datas } );
})

app.listen( 3000, () => {
    console.log( '3000번 포트에서 서버 대기중입니다.'); 
})

-cats.jade

doctype 
html 
  head 
    title Jade Example 
    meta( charset="utf-8" )
  body 
    h1= title 
    ul 
      for item in cats   
        li 
          image( src="./images/" + item.image height="50px" )
          span= item.title

 

구구단 만들기

jade3라는 패키지를 만들고 아래와 같이 디렉터리와 파일을 만들어보자.
jade3

    route

         main.js
    views

         gugudan.jade
         gugudan_ok.jade

    server.js

[master@localhost jade2]$ cd
[master@localhost ~]$ mkdir jade3
[master@localhost ~]$ cd jade3
[master@localhost jade3]$ npm init -y
[master@localhost jade3]$ npm install express
[master@localhost jade3]$ npm install jade

-실행결과

 

코드

 

-main.js

"use strict"

module.exports = ( app ) => {
    app.all( '/gugudan', (req, res) => {
        res.render( 'gugudan' );
    })
    app.all( '/gugudan_ok', (req, res) => {
        console.log( req.query.dan );
        let result = '<table width="800" border="1">';
            result += '<tr align="center">'
            for( let i=1; i<=9; i++ ) {
                result += '<td>' + req.query.dan + ' X ' + i + ' = ' + ( parseInt(req.query.dan) * i) + '</td>';
            }
            result += '</tr>'
            result += '</table>';

        res.render( 'gugudan_ok', { result: result } );
    })
}

-server.js

"use strict"
const express = require( 'express' );
const app = express();

app.set( 'views', __dirname + '/views' );  
app.set( 'view engine', 'jade' );      

const router = require( './routes/main' )( app );

app.listen( 3000, () => {
    console.log( '3000번 포트에서 서버 대기중입니다.'); 
})

-gugudan.jade

doctype 
html(lang="ko")
  head 
    title Gugudan Example
    meta( charset="utf-8" )
  body 
    h1 Hello Gugudan
    hr
    form(action="./gugudan_ok" method="get")
      p 단수입력
        input(type="text" name="dan")
        input(type="submit" value="전송")
        

-gugudan_ok.jade

doctype 
html(lang="ko")
  head 
    title Gugudan_ok Example
    meta( charset="utf-8" )
  body 
    h1 Hello Gugudan Ok
    hr
    - const html = result
    div !{ html }
        

 

만일 post방식으로 할 경우 아래와 같이 body-parser를 사용해야한다.
server.js를 아래와 같이 수정하면 된다.
-server.js

"use strict"
const express = require( 'express' );
const bodyParser = require( 'body-parser' );
const app = express();

app.set( 'views', __dirname + '/views' );  
app.set( 'view engine', 'jade' );      

//body parser process - post방식 데이터 처리를 위한 미들웨어설정
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( { extended: false } ) );

const router = require( './routes/main' )( app );

app.listen( 3000, () => {
    console.log( '3000번 포트에서 서버 대기중입니다.'); 
})


위의 구성을 express-generator를 이용해서 만들어보자.
먼저 리눅스에서 아래와 같이 명령어를 친다.

[master@localhost jade3]$ cd
[master@localhost ~]$ express jade
[master@localhost ~]$ cd jade
[master@localhost jade]$ npm install
[master@localhost jade]$ npm start

이제 브라우저에서 확인해보면 아래와 같이 나온다. 이때 다른 3000번포트 웹서버가 켜져있으면 꺼줘야 한다. 

 

 

 

 

 

 

 

 

 

728x90
반응형
LIST
Comments