我有以下模板。我想在两者之间用逗号显示类别。我该怎么做?
目前使用Categories: {{each categories}} <i>${$value}</i> {{/each}}
注意:最后一项之后应该没有逗号。此外,所有项目都应显示在一行(目前为止)
<script id="Script1" type="text/x-jQuery-tmpl">
<h1>${postTitle}</h1>
<p>
${postEntry}
</p>
{{if categories}}
Categories: {{each categories}} <i>${$value}</i> {{/each}}
{{else}}
Uncategorized
{{/if}}
</script>
<script type="text/javascript">
var blogPostsArray = [
{
postTitle: "Learn jQuery",
postEntry: "Learn jQuery easliy by following.... ",
categories: ["HowTo", "Sinks", "Plumbing"]
},
{
postTitle: "New Tests",
postEntry: "This is a test website"
}
];
$("#blogPostTemplate").tmpl(blogPostsArray).appendTo("#blogPostContainerDiv");
</script>
答案 0 :(得分:1)
这会有用吗?
categories.join(', ');
获取您的字符串值。不知道你会把它放在哪里,但这个例子似乎显示了如何
https://github.com/jquery/jquery-tmpl/blob/master/demos/samplesCore/basic.html
编辑:
请允许我为你做:):))
{{if categories}}
Categories: <i>${categories.join(", ")}</i>
{{else}}
Uncategorized
{{/if}}
答案 1 :(得分:1)
尝试这样做:
<script id="Script1" type="text/x-jQuery-tmpl">
<h1>${postTitle}</h1>
<p>
${postEntry}
</p>
{{if categories}}
Categories: ${categories}
{{else}}
Uncategorized
{{/if}}
</script>
<script type="text/javascript">
var blogPostsArray = [
{
postTitle: "Learn jQuery",
postEntry: "Learn jQuery easliy by following.... ",
categories: ["HowTo", "Sinks", "Plumbing"].join(', ')
},
{
postTitle: "New Tests",
postEntry: "This is a test website"
}
];
$("#blogPostTemplate").tmpl(blogPostsArray).appendTo("#blogPostContainerDiv");
</script>
行categories: ["HowTo", "Sinks", "Plumbing"].join(', ')
将字符串数组连接成一个字符串,以逗号分隔。还更改了模板,以便它只打印类别而不是循环。
答案 2 :(得分:1)
如果您有更复杂的数据,请说:
var blogPostsArray = [
{
postTitle: "Learn jQuery",
postEntry: "Learn jQuery easliy by following.... ",
categories:
[
{
Name="Category 1",
Description="Category 1 description"
},
{
Name="Category 2",
Description="Category 2 description"
}
]
},
{
postTitle: "New Tests",
postEntry: "This is a test website"
}
];
你可以这样做(这也适用于你的数据):
{{if categories }}
<div>
Categories:
{{each(i, category) categories}}
${category.Name}
$(category.Description)
{{if categories.length != (i + 1) }}
,
{{/if}}
{{/each}}
</div>
{{/if}}
希望这有助于某人。