관심분야/퍼블

Underscore.js 사용후기

헤나바나나 2019. 9. 11. 00:31

안녕하세요~

 

지난 프로젝트 개발당시 클라이언트 사이드 템플릿 엔진으로 사용하였던 Underscore.js 에 대해서 공유를 해보려고

합니다. 자바스크팁트 객체등을 다루는 데 있어서 간편하고 유용하게 사용할 수 있었습니다.

 

Underscore.js 란?

함수형 자바스크립트 라이브러리로 자바스크립트의 객체(Objects)와 배열(Arrays)을 다루는 유용한 함수들이 포함되어 있습니다.

 

공식 사이트 : https://underscorejs.org/

 

Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive

underscorejs.org

 

사용법

underscore.js를 다운로드하여 사용하거나 직접 스크립트로 해당 URL을 참조한 뒤

언더스코어 이름처럼 _. 로 선언 후 필요한 함수들을 호출하여 사용합니다. 

 

template 함수 예제입니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(function() {
 
  var person = {
        name'신한DS',
        englishname : 'SHINHAN DS'
  };
 
  
  var template = _.template("hello: <%= name %>");
  var result = template(person);
 
 
  var second_template = _.template("<b><%- englishname %></b>");
  var values = second_template(person);
 
 
  $('#template_ex1').append(result);
  $('#template_ex2').append(values);
 
})();

결과는?? template_ex1, template_ex2 라는 html내 id로 선언된 곳에 아래와 같이 출력 :)

 

hello: 신한DS

SHINHAN DS

 

다음은 목록에 더보기로 append 처리 기능 사용시 사용했던 union 함수와 each 함수를 간단하게 코딩해 보았습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(function() {
  var list = [
    {"id""10""value" : "text 1" }, 
    {"id""11""value" : "text 2" }, 
    {"id""3""value" : "text 3" },
  ];
  
  var add_list = [
    {"id""4""value" : "text 4" },
    {"id""5""value" : "text 5" }
  ];
 
  var unionList = _.union(list, add_list);
  
  var viewOutput = '';
  _.each(unionList, function (data, index, value) {
    var output = '<li>'+data.value +'</li>';
    viewOutput += output;
  });
 
  console.log(viewOutput);
})();

console에 찍히는 결과는?

<li>text 1</li><li>text 2</li><li>text 3</li><li>text 4</li><li>text 5</li>

 

template을 사용하여 렌더링 하고, 서버 단에서 받아오는 json 타입의 데이터들을 collection 함수들을 사용하여 가공하고 보여주는 데 쉽게 처리 할 수 있었습니다. 

 

유용한 함수 몇 개 더 적어본다면...

findWhere_.findWhere(list, properties)

contains_.contains(list, value, [fromIndex]) 

extend_.extend(destination, *sources)

 

단점으로는 프론트 단을 컨트롤 하는 부분이라 퍼블리싱 영역과 애매한 부분이 있어서 화면을 렌더링 하는 부분 시점 등의 충돌이 있어서 어려움이 있었습니다. 퍼블리셔분들의 도움도 많이 받아 해결을 하였고 렌더링 후 이벤트 호출이 제대로 안되는 경우가 있었는데 해당 이벤트를 재호출하거나 시간차를 주어 해결하였습니다.

 

마지막으로! 2019년도 현재 인기많은 템플릿 엔진 순위가 궁금하여 찾아 보았습니다. 

 

자바스크립트 웹 템플릿 엔진 순위 (7위까지만 링크를 걸어보았습니다.)

https://colorlib.com/wp/top-templating-engines-for-javascript/

 

1. mustache

https://mustache.github.io/

 

{{ mustache }}

Logic-less templates. Available in Ruby, JavaScript, Python, Erlang, Elixir, PHP, Perl, Perl6, Objective-C, Java, C#/.NET, Android, C++, CFEngine, Go, Lua, ooc, ActionScript, ColdFusion, Scala, Clojure[Script], Fantom, CoffeeScript, D, Haskell, XQuery, ASP

mustache.github.io

2. Handlebars

http://handlebarsjs.com/

 

Handlebars.js: Minimal Templating on Steroids

Handlebars templates look like regular HTML, with embedded handlebars expressions. {{title}} {{body}} A handlebars expression is a {{, some contents, followed by a }} Learn More: Expressions You can deliver a template to the browser by including it in a ta

handlebarsjs.com

3. doT

https://olado.github.io/doT/

 

doT.js - the fastest and concise javascript template engine for Node.js and browsers

doT.js was created in search of the fastest and concise JavaScript templating function with emphasis on performance under V8 and Node.js. It shows great performance for both Node.js and browsers. During my quest I found 2 template engines that caught my at

olado.github.io

4. EJS

https://ejs.co/

 

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

5. Nunjucks

https://mozilla.github.io/nunjucks/

 

Nunjucks

You've been looking for a more sophisticated templating engine for JavaScript. Here it is. Rich Powerful language with block inheritance, autoescaping, macros, asynchronous control, and more. Heavily inspired by jinja2 Fast & Lean High-performant. Small 8K

mozilla.github.io

6. Underscore

https://underscorejs.org/

 

Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive

underscorejs.org

7. Pug

https://pugjs.org/api/getting-started.html

 

Getting Started – Pug

Getting Started Installation Pug is available via npm: $ npm install pug Overview The general rendering process of Pug is simple. pug.compile() will compile the Pug source code into a JavaScript function that takes a data object (called “locals”) as an arg

pugjs.org

 

읽어주셔서 감사합니다 :)