Last active
June 15, 2023 06:48
-
-
Save fproperzi/71146a06b600232dfddd2e0fe968eee9 to your computer and use it in GitHub Desktop.
one translations file to include in js or php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$jlang = <<<EOT | |
{ | |
"cancel":"Cancella", | |
"close": "Chiudi", | |
"copy": "Copia", | |
"delete": "Elimina", | |
"delete-confirm": "Confermi la cancellazione?", | |
"deleted": "Cancellato", | |
"disabled": "Disabilitati", | |
"done": "Azione compiuta", | |
"validation": { | |
"required": "[%s] è richiesto", | |
"email": "[%s] non è un indirizzo email valido", | |
"min": "[%s] deve essere di almeno %s caratteri", | |
} | |
} | |
EOT; | |
if ( basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"]) ) { // called directly: <script src="this_file.php"></script> | |
echo "const _e = (path) => path.split('.').reduce((o, p) => o && o[p] ? o[p] : path, $jlang);"; | |
} | |
else { // called with include/require from php: include "this_file.php"; | |
$jlang = json_decode($jlang,true); | |
$_e = function($path) use ($jlang) { | |
$p = explode('.', $path); | |
$out = array_reduce($p, function($carry, $item) use($path){ | |
return isset($carry) && isset($carry[$item]) ? $carry[$item] : $path ; | |
},$jlang); | |
return is_scalar($out) ? $out : $path; | |
}; | |
} | |
/** | |
_e($path, 1,2,3,4...) => vsprintf("numbers %d,%d,%d",[1,2,3,4]) | |
*/ | |
function _e () { | |
$args = func_get_args(); | |
$path = $args[0]; // il path sempre in prima posizione | |
$p = explode('.', $path); | |
$out = array_reduce($p, function($carry, $item) use($path){ | |
return isset($carry) && isset($carry[$item]) ? $carry[$item] : $path ; | |
},$GLOBALS['__jlang']); | |
return is_scalar($out) ? vsprintf($out,array_merge(array_slice($args,1),array_fill(0,9,''))) : $path; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment