Reputation: 22662
I have the following template. I want to display the categories with a comma in between. How do I do it?
Currently it is without comma using Categories: {{each categories}} <i>${$value}</i> {{/each}}
Note: There should be no comma after the last item. Also all items should be displaying in one row (as it is currently)
<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>
Upvotes: 1
Views: 998
Reputation: 2073
If you have more complicated data, say:
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"
}
];
You can do the trick in this way (this also acceptable for your data):
{{if categories }}
<div>
Categories:
{{each(i, category) categories}}
${category.Name}
$(category.Description)
{{if categories.length != (i + 1) }}
,
{{/if}}
{{/each}}
</div>
{{/if}}
Hope this helps somebody.
Upvotes: 1
Reputation: 59408
Try doing this instead:
<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>
The line categories: ["HowTo", "Sinks", "Plumbing"].join(', ')
joins the array of strings into one string, separated by commas. Also changed the template so that it just prints the categories instead of looping.
Upvotes: 1
Reputation: 1786
Would this work?
categories.join(', ');
to get your string value. not sure where you would put this but this example seems to show how
https://github.com/jquery/jquery-tmpl/blob/master/demos/samplesCore/basic.html
EDIT:
Allow me to do it for you :):)
{{if categories}}
Categories: <i>${categories.join(", ")}</i>
{{else}}
Uncategorized
{{/if}}
Upvotes: 1