tiene cualquier método como sustituto del mootools en jquery
-
26-09-2019 - |
Pregunta
este es el código 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);
y que jQuery tiene esta Mothod? o como este método?
Solución
No, pero no hay nada que le impida la adición de uno mismo:
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'});
Otros consejos
La respuesta $.nano
tiró de mí para un bucle, ya que los errores si tiene errores tipográficos en su notación de puntos plantilla, y además no permite que todos los caracteres legales como a['foo bar']
es abajo es mi versión como un 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);
}
});
};
Hay algunos plugins que comparten una sintaxis similar al método String.Format en .NET.
Éste aprovecha el plugin jQuery Validar (comúnmente conocer en CDN) .
Ejemplo:
$("button").click(function () {
var str = "Hello {0}, this is {1}";
str = jQuery.validator.format(str, "World", "Bob");
alert("'" + str + "'");
});
El segundo plugin se nombró .NET Estilo Cadena de Formato .
Ejemplo:
var result = $.format("Hello, {0}", "world");
Estos no puede ser exactamente lo que está buscando, pero puede ser útil.
Trate de este plugin https://github.com/trix/nano , la fuente es sólo una pocas líneas
/* 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);
Puede utilizar la notación de puntos {} user.name, sólo simple y potente.