I’ve came up with some custom localization solution for a project I’m working on. The idea is that my HTML can contain this:
<h2 data-l10n="HELLO" data-l10n-params="['Visitor', new Date()]"></h2>
When the page is initiated a javascript function like this runs:
localizeAll: function(sel) {
var selector = sel || document,
$o = $(selector);
$o.find('[data-l10n]').each(
function() {
var $t = $(this),
val = $t.attr('data-l10n'),
params = $t.attr('data-l10n-params'),
po = null;
if (typeof params !== 'undefined') {
po = eval(params);
log(params, po);
}
var res = doLocalize(val, po);
if (res[0] !== '<') {
$t.text(res);
} else {
$t.text(val);
}
});
}
So basically we search for any elements that have a data-l10n-attribute and call doLocalize() for each of those objects. Additionally, the element can have a data-l10n-params-attribute, which is just a string literal that can be parsed to an array. This string is evaluated (params string becomes po array) and po is supplied to doLocalize() as the optional second parameter.
Hence, the output in Firebug (from log(params, po); statement) is:
['Vistor', new Date()] ["Vistor", Date {Thu Nov 17 2011 10:10:31 GMT+0100 (CET)}]
So yes, I’m using eval. And yes, I know that “eval is evil”. But occasionally, I need to pass a parameter to doLocalize().
How could this be done without eval?
I think your problem is that you are effectively embedding JavaScript in HTML (which is against the unobtrusive JavaScript principle).
In your place I would add an extra
l18n-params.jsfile with the following contents:Now instead of reading the params from HTML attribute and evaluating just call: