2012-05-31 1 views
3

예에서 임의의 문자열을 연결 :Handlebars.js - 표현

@{{username}} 

: 내가 이런 짓을 했을까 사용자 이름에 "@"를 추가하고 싶었다 경우 handlebars.js를 사용

그러나 사용자 정의 도우미를 사용하여 표현식뿐만 아니라 전체 텍스트 블록 ("@"포함)에 적용하려면 어떻게해야합니까? 이런 식으로 뭔가 ...

handlebars.registerHelper('color', function(text) { 
    return text.red; 
}); 

{{color "@"username}} 

위의 템플릿이 유효하지 않습니다,하지만 당신은 아이디어를 얻을 ...

답변

6

당신은 예를 들어,이 작업을 수행 할 수 있습니다

<script id="template" type="text/x-handlebars-template"> 
    <ul> 
     {{#each links}} 
     <li><a href="{{ url }}">{{{color prefix title}}}</a></li> 
     {{/each}} 
    </ul> 
</script> 
<script> 
Handlebars.registerHelper("color", function(prefix, title) { 
    return '<span style="color: blue">' + (prefix ? prefix : "@") + title + '</span>'; 
}); // "@" is the default prefix 

source = document.getElementById("template").innerHTML; 
template = Handlebars.compile(source); 
document.write(template({ 
    links: [ 
     {title: "prologin", prefix: "#", link: "http://prologin.org"}, 
     {title: "1.2.1", prefix: "§", link: "#paragraph-121"}, 
     {title: "jjvie", link: "http://twitter.com/jjvie"}, 
    ] 
})); 
</script> 

<span class="username"></span> 또는 <hl></hl>을 것입니다 훨씬 나아질거야.