오브젝트의 속성을 루프하는 빌트인 방법이 있습니까?
오브젝트 속성을 루핑하는 콧수염/핸들바 방법이 있습니까?
그래서...
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
}
그러면 템플릿 엔진에서 다음과 같은 작업을 수행할 수 있습니까?
for(var prop in o)
{
// with say, prop a variable in the template and value the property value
}
?
핸들바 1.0rc1 이후 지원 기능 내장
Handlebars.js에 이 기능의 지원이 추가되어 외부 도우미가 필요하지 않습니다.
사용방법
어레이의 경우:
{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
객체의 경우:
{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
테스트를 통과한 속성만 열거됩니다.
도우미로서 실장하는 것은 매우 간단합니다.
Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
for(var prop in context)
{
ret = ret + options.fn({property:prop,value:context[prop]});
}
return ret;
});
그런 다음 이렇게 사용:
{{#eachProperty object}}
{{property}}: {{value}}<br/>
{{/eachProperty }}
편집: 핸들바에는, 이것을 실현하는 방법이 짜넣어져 있습니다.상기 선택한 답변을 참조해 주세요.밋밋한 콧수염으로 작업하는 경우에도 아래 사항이 적용됩니다.
콧수염은 배열 내의 아이템에 대해 반복할 수 있습니다.따라서 콧수염이 작업할 수 있는 형식으로 포맷된 별도의 데이터 개체를 만드는 것이 좋습니다.
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };
for (var prop in o){
if (o.hasOwnProperty(prop)){
mustacheFormattedData['people'].push({
'key' : prop,
'value' : o[prop]
});
}
}
콧수염 템플릿은 다음과 같습니다.
{{#people}}
{{key}} : {{value}}
{{/people}}
다음 URL에서 "Non-Empty Lists" 섹션을 확인하십시오.https://github.com/janl/mustache.js
Ember와 함께 사용할 수 있도록 업데이트된 @Ben의 답변입니다.를 사용해야 합니다.Ember.get컨텍스트가 문자열로 전달되기 때문입니다.
Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
var newContext = Ember.get(this, context);
for(var prop in newContext)
{
if (newContext.hasOwnProperty(prop)) {
ret = ret + options.fn({property:prop,value:newContext[prop]});
}
}
return ret;
});
템플릿:
{{#eachProperty object}}
{{key}}: {{value}}<br/>
{{/eachProperty }}
@Amit의 답변은 콧수염과 핸들바 양쪽에서 사용할 수 있기 때문에 좋다.
핸들바만의 솔루션에서는 몇 가지 본 적이 있으며each_with_keyhttps://gist.github.com/1371586에서 block helper가 가장 좋습니다.
- 먼저 오브젝트 리터럴을 재구성할 필요 없이 오브젝트 리터럴을 반복할 수 있습니다.
- 이를 통해 키 변수라고 하는 것을 제어할 수 있습니다.다른 많은 솔루션에서는 이름이 붙은 오브젝트 키를 사용할 때 주의해야 합니다.
'key', 또는'property',기타.
특정 필드만 순서대로 표시할 수 있는 사용 사례인 Ben의 솔루션 덕분에
반감을 가지고
코드:
handlebars.registerHelper('eachToDisplayProperty', function(context, toDisplays, options) {
var ret = "";
var toDisplayKeyList = toDisplays.split(",");
for(var i = 0; i < toDisplayKeyList.length; i++) {
toDisplayKey = toDisplayKeyList[i];
if(context[toDisplayKey]) {
ret = ret + options.fn({
property : toDisplayKey,
value : context[toDisplayKey]
});
}
}
return ret;
});
원본 개체:
{ locationDesc:"abc", name:"ghi", description:"def", four:"you wont see this"}
템플릿:
{{#eachToDisplayProperty this "locationDesc,description,name"}}
<div>
{{property}} --- {{value}}
</div>
{{/eachToDisplayProperty}}
출력:
locationDesc --- abc
description --- def
name --- ghi
이는 데이터를 미리 포맷하지 않고 렌더링 중에 가져오지 않고 콧수염J에 대한 도우미 기능입니다.
var data = {
valueFromMap: function() {
return function(text, render) {
// "this" will be an object with map key property
// text will be color that we have between the mustache-tags
// in the template
// render is the function that mustache gives us
// still need to loop since we have no idea what the key is
// but there will only be one
for ( var key in this) {
if (this.hasOwnProperty(key)) {
return render(this[key][text]);
}
}
};
},
list: {
blueHorse: {
color: 'blue'
},
redHorse: {
color: 'red'
}
}
};
템플릿:
{{#list}}
{{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}
출력:
color: blue
color: red
(순서는 랜덤일 수 있습니다.지도입니다)원하는 맵 요소를 알고 있으면 도움이 될 수 있습니다.거짓된 가치를 조심해요.
이전 버전을 사용하고 있었습니다.1.0.beta.6핸들 바의 경우 1.1~1.3 사이에 이 기능이 추가되어 1.3.0으로 업데이트하면 문제가 해결되었습니다.사용 방법은 다음과 같습니다.
사용방법:
{{#each object}}
Key {{@key}} : Value {{this}}
{{/people}}
언급URL : https://stackoverflow.com/questions/9058774/is-there-a-built-in-way-to-loop-through-the-properties-of-an-object
'programing' 카테고리의 다른 글
| 어떤 Java Maven 버전을 사용하여 실행하는지 확인하고 변경하려면 어떻게 해야 합니까? (0) | 2022.11.30 |
|---|---|
| 넷빈을 실행하는 Java 플랫폼 변경 (0) | 2022.11.30 |
| JavaScript의 클래스 대 스태틱 메서드 (0) | 2022.11.30 |
| JavaScript의 child Nodes와 child Nodes의 차이점은 무엇입니까? (0) | 2022.11.20 |
| MariaDB/MySQL 쿼리는 대소문자를 구분합니까? (0) | 2022.11.20 |