2012-09-25 31 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