2012-02-04 50 views
1

我有以下模板。我想用中間的逗號來顯示類別。我該怎麼做?帶逗號的jQuery模板格式化

目前,它是在不使用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

看到我更新的answser – 2012-02-04 11:26:50

回答

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}} 
+0

其實它並沒有比這更簡單。您只需在模板中更改'Categories:{{each categories}} $ {$ value} {{/每個}}'類別: $ {categories.join(「,」)}'。實際上它比原來更簡單:-) – Hubro 2012-02-04 12:09:09

+0

感謝@Codemonkey – 2012-02-05 10:13:48

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(', ')加入陣列字符串轉換爲一個字符串,用逗號分隔。還更改了模板,以便它只打印類別而不是循環。

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}} 

希望這有助於人。