템플릿 엔진으로 언더스코어.js를 사용하는 방법
서버 사이드 언어로서 기능적인 언어로서 javascript의 새로운 사용법을 배우려고 합니다.며칠 전에 node.js와 express framework에 대해 들었습니다.그리고 유틸리티 함수의 세트로 언더스코어.js에 대해 알게 되었습니다.이 질문은 stackoverflow에서 확인되었습니다.템플릿 엔진으로 underscore.js를 사용할 수 있다고 합니다.특히 고급 Javascript에 경험이 적은 빅이너를 위해 Underscore.templating을 사용하는 방법에 대한 좋은 튜토리얼은 누구나 알고 있습니다.감사해요.
밑줄 템플릿에 대해 알아야 할 모든 내용은 여기에 나와 있습니다.주의할 점은 다음 3가지뿐입니다.
<% %>
를 실행합니다. - 코드 실행 - 부- - - - 、 - - - - - - - - 、<%= %>
합니다. - 템플릿에 값을 인쇄합니다.<%- %>
값을 합니다.HTML 이스케이프 - HTML 이스케이프 값입니다.
그게 다예요.
간단한 예:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
tpl({foo: "blahblah"})
됩니다.<h1>Some text: blahblah</h1>
<!-- Install jQuery and underscore -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<!-- Create your template -->
<script type="foo/bar" id='usageList'>
<table cellspacing='0' cellpadding='0' border='1' >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<%
// repeat items
_.each(items,function(item,key,list){
// create variables
var f = item.name.split("").shift().toLowerCase();
%>
<tr>
<!-- use variables -->
<td><%= key %></td>
<td class="<%= f %>">
<!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
<h3><%- item.name %></h3>
<p><%- item.interests %></p>
</td>
</tr>
<%
});
%>
</tbody>
</table>
</script>
<!-- Create your target -->
<div id="target"></div>
<!-- Write some code to fetch the data and apply template -->
<script type="text/javascript">
var items = [
{name:"Alexander", interests:"creating large empires"},
{name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"},
{name:"..."},
{name:"Yolando", interests:"working out"},
{name:"Zachary", interests:"picking flowers for Angela"}
];
var template = $("#usageList").html();
$("#target").html(_.template(template,{items:items}));
</script>
- JsFiddle 고마워 @PHEARST!
- JsFiddle(최신)
- 첫 글자로 그룹화된 JsFiddle List(이미지, 함수 호출, 서브템플릿 포함 복잡한 예)는 포크입니다! 즐거운 시간 되세요...
- 아래 @tarun_telang에 의해 언급된 XSS 해킹의 JsFiddle 데모
- JsFiddle 서브템플릿을 수행하기 위한 비표준 방법 중 하나
가장 간단한 형태에서는 다음과 같이 사용할 수 있습니다.
var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'
템플릿을 여러 번 사용할 경우 보다 빠르게 컴파일해야 합니다.
var template = _.template('<li><%= name %></li>');
var html = [];
for (var key in names) {
html += template({ name: names[i] });
}
console.log(html.join('')); //Outputs a string of <li> items
저는 개인적으로 콧수염 스타일의 구문을 선호합니다.템플릿 토큰 마커를 조정하여 이중 중괄호를 사용할 수 있습니다.
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
var template = _.template('<li>{{ name }}</li>');
템플릿 제작 서류는 부분적이라 출처를 지켜봤다.
_.template 함수에는 다음 3개의 인수가 있습니다.
- String text : 템플릿 문자열
- 오브젝트 데이터 : 평가 데이터
- 오브젝트 설정 : 로컬 설정, _.templateSettings는 글로벌 설정 오브젝트입니다.
지정된 데이터(또는 null)가 없는 경우 렌더링 함수가 반환됩니다.인수에는 다음 1개가 있습니다.
- 오브젝트 데이터: 위의 데이터와 동일합니다.
설정에는 3개의 regex 패턴과 1개의 static 파라미터가 있습니다.
- RegExp evaluate : 템플릿 문자열의 "<%code%>"
- 템플릿 문자열의 RegExp 보간 : "<%=code%>"
- RegExp 이스케이프 : "<%-code%>"
- String variable : 옵션, 템플릿 문자열의 데이터 파라미터 이름
평가 섹션의 코드는 단순하게 평가됩니다.이 섹션의 문자열을 __p+="controlling" 명령을 사용하여 평가된 템플릿에 추가할 수 있지만, 이는 권장되지 않습니다(템플릿 인터페이스의 일부가 아님). 대신 interpolate 섹션을 사용하십시오.이 섹션 유형은 if 또는 for와 같은 블록을 템플릿에 추가하기 위한 것입니다.
보간 섹션의 코드 결과가 평가된 템플릿에 추가됩니다.null이 반환되면 빈 문자열이 추가됩니다.
이스케이프 섹션은 지정된 코드의 반환값에 대해 _.escape를 사용하여 html을 이스케이프합니다.따라서 인터폴 섹션의 _.escape(코드)와 비슷하지만 코드를 _.escape로 전달하기 전에 \n과 같은 공백 문자로 이스케이프됩니다.왜 그렇게 중요한지는 모르겠지만, 코드에는 있지만, 인터폴과 _.escape에서 잘 작동하는데, _.escape는 공백 문자를 벗어나지 않습니다.
기본적으로는 데이터 파라미터는 (데이터){...에 의해 전달됩니다.} 스테이트먼트. 단, 이러한 종류의 평가는 명명된 변수를 사용한 평가보다 훨씬 느립니다.따라서 변수 매개 변수로 데이터 이름을 지정하는 것이 좋습니다.
예를 들어 다음과 같습니다.
var html = _.template(
"<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" +
"as the \"<%= _.escape(o.text) %>\" and the same<br />" +
"as the \"<%- o.text %>\"</pre>",
{
text: "<b>some text</b> and \n it's a line break"
},
{
variable: "o"
}
);
$("body").html(html);
결과.
The "<b>some text</b> and
it's a line break" is the same
as the "<b>some text</b> and
it's a line break" and the same
as the "<b>some text</b> and
it's a line break"
템플릿을 사용하여 기본 설정을 덮어쓰는 더 많은 예를 http://underscorejs.org/ #template 에서 찾을 수 있습니다.
템플릿을 로드하면 많은 옵션이 있지만 마지막에 항상 템플릿을 문자열로 변환해야 합니다.위의 예시와 같이 일반 문자열로 지정할 수도 있고 스크립트 태그에서 로드하여 jquery의 .html() 함수를 사용하거나 require.js의 tpl 플러그인을 사용하여 별도의 파일에서 로드할 수도 있습니다.
템플 대신 간결하게 돔 트리를 만드는 또 다른 옵션입니다.
아주 간단한 예를 들겠습니다.
1)
var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate);
결과는 다음과 같습니다.
Welcome you are at mysite.This has been created by john whose age is 25.
2) 이것은 템플릿입니다.
<script type="text/template" id="template_1">
<% _.each(items,function(item,key,arr) { %>
<li>
<span><%= key %></span>
<span><%= item.name %></span>
<span><%= item.type %></span>
</li>
<% }); %>
</script>
이것은 html입니다.
<div>
<ul id="list_2"></ul>
</div>
json 객체와 템플릿을 html에 넣는 javascript 코드입니다.
var items = [
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
}
];
$(document).ready(function(){
var template = $("#template_1").html();
$("#list_2").html(_.template(template,{items:items}));
});
익스프레스면 너무 쉬워.필요한 것은 노드에서 통합 모듈을 사용하는 것뿐이므로 이를 설치해야 합니다.
npm install consolidate --save
다음으로 디폴트엔진을 html 템플릿으로 변경해야 합니다.
app.set('view engine', 'html');
html 확장자에 언더스코어 템플릿엔진을 등록합니다.
app.engine('html', require('consolidate').underscore);
끝났어요!
다음으로 로드 예를 들어 'index.html'이라는 템플릿의 예를 나타냅니다.
res.render('index', { title : 'my first page'});
언더스코어 모듈을 장착해야 할 수도 있습니다.
npm install underscore --save
도움이 되셨길 바랍니다!
중요한 발견을 하나 더 공유하고 싶었습니다.
<%= 변수 =>를 사용하면 사이트 간 스크립팅 취약성이 발생할 수 있습니다.따라서 <%-variable ->를 사용하는 것이 보다 안전합니다.
사이트 간 스크립팅 공격을 방지하기 위해 <%=를 <%->로 대체해야 했습니다.이것이 퍼포먼스에 영향을 미칠지 어떨지 확실하지 않습니다.
Lodash도 마찬가지입니다.처음에는 다음과 같이 스크립트를 작성합니다.
<script type="text/template" id="genTable">
<table cellspacing='0' cellpadding='0' border='1'>
<tr>
<% for(var prop in users[0]){%>
<th><%= prop %> </th>
<% }%>
</tr>
<%_.forEach(users, function(user) { %>
<tr>
<% for(var prop in user){%>
<td><%= user[prop] %> </td>
<% }%>
</tr>
<%})%>
</table>
이제 다음과 같이 간단한 JS를 작성합니다.
var arrOfObjects = [];
for (var s = 0; s < 10; s++) {
var simpleObject = {};
simpleObject.Name = "Name_" + s;
simpleObject.Address = "Address_" + s;
arrOfObjects[s] = simpleObject;
}
var theObject = { 'users': arrOfObjects }
var compiled = _.template($("#genTable").text());
var sigma = compiled({ 'users': myArr });
$(sigma).appendTo("#popup");
여기서 popoup은 테이블을 생성할 div입니다.
언급URL : https://stackoverflow.com/questions/4778881/how-to-use-underscore-js-as-a-template-engine
'programing' 카테고리의 다른 글
강조 표시/선택한 텍스트를 가져옵니다. (0) | 2022.11.17 |
---|---|
fragment화 권한을 확인하는 방법 (0) | 2022.11.17 |
SQLSTATE [ 42000 ]:구문 오류 또는 액세스 위반: SELECT 목록의 1055 식 #3이 GROUP BY 절에 없고 집계되지 않은 것을 포함합니다. (0) | 2022.11.17 |
python에서 반복적으로 폴더 삭제 (0) | 2022.11.17 |
React.js에서 컴포넌트의 소품을 갱신할 수 있습니까? (0) | 2022.11.17 |