2010-04-12 14 views
1

ce code est Mootools:a une méthode comme substitut de Mootools dans jquery

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

et ne jquery a cette mothod? ou comme cette méthode?

+0

http://www.planabc.net/2011/05/31/simple_javascript_template_substitute/ https://github.com/yui/yui3/blob/master/src/substitute/js/substitute.js Voici La solution de YUI. –

Répondre

11

Non, mais il n'y a rien qui vous empêche d'ajouter vous-même:

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 in sub" est une erreur – zjm1126

+0

Fonctionne pour moi ... Quelle erreur est lancée? – James

+0

oh, désolé, mon tort, c'est bon ~ – zjm1126

0

Il y a quelques plugins qui partagent une syntaxe similaire à la méthode String.Format dans .NET.

This one exploite le plugin jQuery Validate (généralement trouvé sur les CDN).

Exemple:

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

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

Le second plugin est nommé .NET Style String Format.

Exemple:

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

Ceux-ci peuvent ne pas être exactement ce que vous cherchez, mais ils peuvent être utiles.

0

Essayez ce plugin https://github.com/trix/nano, la source est juste quelques lignes

/* 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); 

Vous pouvez utiliser la notation dot {de} user.name, tout simple et puissant.

0

La réponse $.nano m'a jeté pour une boucle car il des erreurs si vous avez des fautes de frappe dans votre notation de point de modèle, et en outre, il ne permet pas tous les caractères légaux comme a['foo bar'] donc ci-dessous est ma version en tant que plugin $.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); 
     } 

    }); 
};