Skip to content

Instantly share code, notes, and snippets.

@jongpak
Created February 19, 2017 13:48
Show Gist options
  • Save jongpak/c1e9ab65924caf499e527a12561ed9b0 to your computer and use it in GitHub Desktop.
Save jongpak/c1e9ab65924caf499e527a12561ed9b0 to your computer and use it in GitHub Desktop.
Underscore.js template
<!DOCTYPE html>
<html>
<head>
<script src="//underscorejs.org/underscore-min.js"></script>
<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
<meta charset=utf-8 />
<title>underscore.js template</title>
</head>
<body>
<h1>Underscore.js template example</h1>
<div id="content"></div>
<script type="text/template" id="itemTemplate">
<h2><%= title %></h2>
<ul>
<%for(var i = 0; i < items.length; i++) { %>
<li><%= items[i].name %></li>
<%} %>
</ul>
</script>
<script>
var itemTemplate = $('#itemTemplate').html();
var items = [
{ name: "test1"},
{ name: "test2"},
{ name: "test3"}
];
var complied = _.template( itemTemplate );
var template = complied({ title: 'todo', items: items });
$('#content').html( template );
</script>
</body>
</html>
@jongpak
Copy link
Author

jongpak commented Feb 19, 2017

실행결과는 다음과 같음

image

@jongpak
Copy link
Author

jongpak commented Feb 20, 2017

DOM방식에서 템플릿으로 분리해가는 과정 설명:
http://www.codereadability.com/constructing-html-with-templates/

많이 쓰는 템플릿엔진으로 mustache.js 도 있음
https://mustache.github.io/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment