2010-04-12 44 views
1

這是mootools的代碼:具有像的jquery的mootools的替代任何方法

var myString = "{subject} is {property_1} and {property_2}."; 
var myObject = {subject: 'Jack Bauer', property_1: 'our lord', property_2: 'savior'}; 
myString.substitute(myObject); 

和確實jQuery有此評判?或者像這樣的方法?

+0

http://www.planabc.net/2011/05/31/simple_javascript_template_substitute/ https://github.com/yui/yui3/blob/master/src/substitute/js/substitute.js這裏是YUI的解決方案。 – 2011-11-13 05:07:06

回答

11

沒有,但沒有什麼阻止你自己添加它:

jQuery.substitute = function(str, sub) { 
    return str.replace(/\{(.+?)\}/g, function($0, $1) { 
     return $1 in sub ? sub[$1] : $0; 
    }); 
}; 

// usage: 
jQuery.substitute('{foo}', {foo:'123'}); 
+0

「子$ 1」是一個錯誤 – zjm1126 2010-04-12 10:55:53

+0

適用於我......拋出什麼錯誤? – James 2010-04-12 11:05:02

+0

哦,對不起,我錯了,那很好〜 – zjm1126 2010-04-13 01:05:05

0

有一些插件共享類似的語法在.NET String.Format方法。

This one利用jQuery Validate插件(通常在CDN上發現)。

實施例:

$("button").click(function() { 
    var str = "Hello {0}, this is {1}"; 

    str = jQuery.validator.format(str, "World", "Bob"); 
    alert("'" + str + "'"); 
}); 

第二插件被命名爲.NET Style String Format

例子:

var result = $.format("Hello, {0}", "world"); 

這些可能不是你在尋找什麼,但他們可能是有用的。

0

試試這個插件https://github.com/trix/nano,來源是短短的幾行

/* Nano Templates (Tomasz Mazur, Jacek Becela) */ 
(function($){ 
    $.nano = function(template, data) { 
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) { 
     var keys = key.split("."), value = data[keys.shift()]; 
     $.each(keys, function() { value = value[this]; }); 
     return (value === null || value === undefined) ? "" : value; 
    }); 
    }; 
})(jQuery); 

您可以使用點符號{user.name},只是簡單的,功能強大。

0

$.nano答案扔我一個循環,因爲它錯誤,如果你在你的模板圓點符號任何錯別字,而且它不允許像a['foo bar']所有合法字符所以下面是我的版本作爲$.substitute插件:

/* 
* JQuery Substitute method allows for simple templating using JS Object dot notation. 
* Contribute link: https://gist.github.com/danielsokolowski/0954fc2a767f441720b9 
* 
* @param strTemplate - string contain the replacement tokens 
* @param objData - an Object represetnting your replacmenet values 
* 
* Example: 
* var strTemplate = 'Hello {user.name}'  
* var strDatra = {'user': 'Daniel Sokolowski'} 
* alert($.substitute(strTemplate, objData)); // outputs 'Hello Daniel Sokolowski' 
* 
*/ 
$.substitute = function(strTemplate, objData) { 
    return strTemplate.replace(/\{([^{}]*)\}/g, function(math, subMatch1) { 
     try { 
      var keys = subMatch1.split("."); 
      var value = objData[keys.shift()]; // return first element and update the original array 
      while (keys.length !== 0) { // keep returning properties 
       value = value[keys.shift()] 
      } 
      return String(value); 
     } catch (err) { // return any errors as a string 
      return String(value); 
     } 

    }); 
}; 
相關問題