2012-09-25 25 views
14

我想對將輸出到視圖的某些文本使用Ext的String方法。如何調用XTemplate中的函數(itemTpl)

例如:

itemTpl: [ 
    ... 
    '<tpl switch="post_type">', 
    '<tpl case="new_user">', 
     '<p>{post_text_teaser}</p>', 
     '<p>{timestamp}</p>', 
    '<tpl default>', 
     '<p>' + Ext.String.ellipsis(+ '{post_text_teaser}' + \, 4) + '</p>', 
    ... 
].join(''), 

但當然在線路10串聯是非法的。

你知道是否有可能或如何正確地做到這一點?

+0

@johan和@sra記錄OP中的編輯 - 'itemTpl'末尾有'.join('')' - 當包含函數時會出現問題嗎? – pepe

+0

只要你運行模板爲XTemplate這應該是沒有問題的 – sra

回答

18

裏面的函數這應該解決您的問題:

'<tpl switch="post_type">', 
     '<tpl case="new_user">', 
      '<p>{post_text_teaser}</p>', 
      '<p>{timestamp}</p>', 
     '<tpl default>', 
      '<p>{[Ext.String.ellipsis(values.post_text_teaser,4,false)]}</p>', 
    '</tpl>' 

你可以找到更多關於XTemplate的信息在Sencha Docs

模板成員函數的事情是,據我所知,你不能直接在itemTpl中定義它們,但需要明確定義一個新的XTemplate,然後在你的itemTpl中使用它。見例如:

var tpl = new XTemplate(
    '<tpl switch="post_type">', 
     '<tpl case="new_user">', 
      '<p>{post_text_teaser}</p>', 
      '<p>{timestamp}</p>', 
     '<tpl default>', 
      '<p>{[this.shorten(values.post_text_teaser)]}</p>', 
    '</tpl>', 
    {   
     shorten: function(name){ 
      return Ext.String.ellipsis(name,4,false); 
     } 
    } 
); 

... 

itemTpl: tpl, 

... 

Senchafiddle example

將在下面的代碼這應該工作正常(剛從XTemplate插入上面的代碼)。

itemTpl: new XTemplate(...), 

Senchafiddle example

希望這sortens吧!

編輯注意到我哈得錯過了結束標記,有時它的工作原理沒有他們,但它是很好的做法,始終使用它們,因爲它們可能會導致有趣的錯誤(在這種情況下,缺少對所生成的代碼支架)。

+0

絕對+1 可以解釋爲什麼這個不可能工作用成員方法? – sra

+0

已將關於成員函數的信息添加到答案 – zelexir

+0

是的,就像魅力一樣工作 - thx zelexir和@sra爲您的建議 – pepe

1

Note: The example below does not work as expected! Look at zelexir answer for clarification!

您可以使用memberfunctions

itemTpl: [ 
    ... 
    '<tpl switch="post_type">', 
    '<tpl case="new_user">', 
     '<p>{post_text_teaser}</p>', 
     '<p>{timestamp}</p>', 
    '<tpl default>', 
     '<p>{[this.doAction(post_text_teaser)]}</p>', 
    ..., 
    { 
     // XTemplate configuration: 
     disableFormats: true, 
     // member functions: 
     doAction: function(name){ 
      return Ext.String.ellipsis(name + "\", 4); 
     } 
    } 
] 
+0

與@johan相同的東西 - ','導致錯誤 – pepe

+0

@torr那麼它需要被包裹到''我想,但無論如何,它似乎至少在我的沙箱裏,我不會按預期工作......我會繼續測試它 – sra

+0

'join'會搞亂'''的使用,所以它需要在函數參數中使用'''。所以這樣可以消除錯誤,但我仍然無法得到這個工作... – pepe

0

您可以使用模板

itemTpl: [ 
    ... 
    '<tpl switch="post_type">', 
    '<tpl case="new_user">', 
     '<p>{post_text_teaser}</p>', 
     '<p>{timestamp}</p>', 
    '<tpl default>', 
     '<p>{[this.concatenate(values.post_text_teaser)]}</p>', 
    ..., 
    { 
     concatenate: function(teaser) { 
       return Ext.String.ellipsis(+ teaser + \, 4); 
     } 
    } 
] 
+0

這個解決方案給了我'Uncaught SyntaxError:意外的令牌,'在控制檯上:( - '','是我們試圖逃跑的那個 – pepe