我有一些来自JSON文件的字符串。其中一些包含特殊的字符" - "," - "或者是空的
{
"title": "Rihanna - Pour it up"
},
{
"title" : "Lady Gaga -- Bad Romance"
},
{
"title" : "Live from Golden Globes"
}
所以,我有这个注册表:
Handlebars.registerHelper('titleSplit', function(title) {
if(title.indexOf('-') === -1){
return new Handlebars.SafeString("<h2>" + title + "</h2>" + "<br />" + "<h2> </h2>");
}
if(title.indexOf('--') === -2){
var t = title.split(" -- ");
return new Handlebars.SafeString("<h2>" + t[1] + "</h2>" + " <br/> " + "<h2>" + t[0] + "</h2>");
}
else {
var t = title.split(" - ");
return new Handlebars.SafeString("<h2>" + t[1] + "</h2>" + " <br/> " + "<h2>" + t[0] + "</h2>");
}
});
并在我的Handlebars HTML模板中:
<div>
{{titleSplit title}}
</div>
它的工作正常,但--
标题显示如下:
Undefined
Lady Gaga -- Bad Romance
这可能是什么问题?
答案 0 :(得分:1)
我不完全确定你想要的输出应该是什么。但这是工作助手和输出
Handlebars.registerHelper('titleSplit', function(title) {
var titles;
if(title.indexOf(' - ') >= 0){
titles = title.split(' - ');
} else if(title.indexOf(' -- ') >= 0){
titles = title.split(' -- ');
} else {
titles = title.split();
titles[1] = '';
}
return new Handlebars.SafeString(
"<h2>" + titles[1] + "</h2>" + " <br/> " + "<h2>" + titles[0] + "</h2>");
});
//output
Pour it up
Rihanna
Bad Romance
Lady Gaga
Live from Golden Globes