This repository has been archived on 2025-01-01. You can view files and clone it, but cannot push or open issues or pull requests.
moodle-local_treestudyplan/amd/src/util/string-helper.js
2023-10-18 08:46:44 +02:00

76 lines
No EOL
2.5 KiB
JavaScript

import {get_strings} from 'core/str';
import {getStrings} from 'core/str';
/* Determine the proper getstrings function to use (MDL4.3+ recommends use of getStrings, which is jquery independent) */
const getstr_func = (getStrings !== undefined)?getStrings:get_strings;
/**
* Load the translation of strings from a strings object
* @param {Object} strings The map of strings
* @returns {Object} The map with strings loaded in
*/
export function load_strings(strings){
for(let idx in strings){
let stringkeys = [];
for(const handle in strings[idx]){
const key = strings[idx][handle];
let parts = key.split(/[$@]/);
let identifier = parts[0];
let component = (parts.length > 1)?parts[1]:'local_treestudyplan';
stringkeys.push({ key: identifier, component: component});
}
getstr_func(stringkeys).then(function(str){
let i = 0;
for(const key in strings[idx]){
strings[idx][key] = str[i];
i++;
}
});
}
return strings;
}
/**
* Load the translation of strings from a strings object based on keys
* Used for loading values for a drop down menu or the like
* @param {Object} string_keys The map of stringkeys
* @returns {Object} The map with strings loaded in
*/
export function load_stringkeys(string_keys){
for(let idx in string_keys){
// Get text strings for condition settings
let stringkeys = [];
for(const i in string_keys[idx]){
const key = string_keys[idx][i].textkey;
let parts = key.split("$");
let identifier = parts[0];
let component = (parts.length > 1)?parts[1]:'local_treestudyplan';
stringkeys.push({ key: identifier, component: component});
}
getstr_func(stringkeys).then(function(strings){
for(const i in strings) {
const s = strings[i];
const l = string_keys[idx][i];
l.text = s;
}
});
}
return string_keys;
}
/**
* String formatting function - replaces {name} in string by value of same key in values parameter
* @param {string} str String t
* @param {object} values Object containing keys to replace {key} strings with
* @returns Formatted string
*/
export function strformat(str,values) {
return str.replace(/\{(\w+)\}/g, (m, m1) => {
if (m1 && values.hasOwnProperty(m1)) {
return values[m1];
} else {
return m;
}
});
}