jQuery扩展推荐 - jquery.strings.js

直都在用jQuery在做前端页面的效果设计,主要还是因为其简单的DOM查找,遍历及操控。在使用中经常会碰到创建页面元素的情况,而大部分情况下,需要创建的元素都可以抽象成为某种模板。如果你也经常碰到这样的情况,我要向你推荐一款扩展,其仿照Python的string template方式一定会让你获得一种全新的体验。

jquery.string 是一款包含在 jQuery utils 的字符串格式化相关的扩展包,使用方法非常简单:

  1. 定义模板

使用如下的方式进行模板定义,第一个参数是模板名称,主要为了方便调用; 第二个参数是模板的具体内容,可以是单个字符串,也可以是字符串数组。

$.tpl('tweet', [
    '<div id="tweet-{id:s}" class="tweet">',
        '<div class="tweet-body"><b>@{from:s}</b>: {body:s}',
            '(<a href="{href:s}" class="tweet-date">',
                '<abbr title="{timestamp:s}">{timesince:s}</abbr>',
            '</a>)',
        '</div>',
    '</div>'
]);

由于javascript中并没有像Python一样提供多行字符串的输入方式,使用数组方式来定义模板可以给之后的debug提供不错的体验。我也没看过它的源码,不知道在数组和字符串两种格式上哪个效率更高,不过如果需要的话,用个正则替换就能将这个数组给替换称单个字符串了,也不是什么麻烦的事。

  1. 套用模板

在Python中,可以使用字典的方式来渲染字符串模板:

'%(name1)s likes %(name2)s because %(name2)s is very beautiful.' % {
  'name1': 'Bob', 'name2': 'Lily'}

jquery.string使用了与Python类似的渲染方法,拿上文定义的tweet的模板为例,可以使用如下的方法使用该模板:

$.tpl('tweet', {
     id: tweet.id,
     body: tweet.body,
     from: tweet.screen_name,
     timestamp: tweet.pub_time,
     timesince: $.timeago(tweet.pub_time)
}, true); // 返回字符串

需要注意的是第三个参数,如果不提供该参数或赋为false的话,调用返回值是一个jQuery对象。如果你希望得到的是字符串形式,需要显式地传递一个真值。

最后,需要提一下的是,在代码依赖上,jquery.string依赖于jquery.utils,而jquery.utils当然还要依赖jquery,所以在使用string扩展时,需要将这三个文件都依次声明在HTML的js引用里才行。嗯,剩下的就没什么好说的了,Good Luck!

对“jQuery扩展推荐 - jquery.strings.js”的1条评论

  1. Avatar

    In this article you will discover some tools and techniques that are essential for your wooden tool box, however keep in mind that your project is unique and might require some tool or technique that is not so generic. They have achieved this, simply by understanding why you eat what you eat. That willingness to protect themselves and survive! <a href=http://lopolikuminr.com>spritzing</a> They can be a little selfish, but not intentionally, and are good leaders. Both are an ideal match for each other due to their similar nature.

发表评论

评论备注:

  1. 留言时的头像是Gravatar提供的服务。
  2. By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution. So, you don't fully own your words, so to speak.