Skip to content

Instantly share code, notes, and snippets.

@ttsukagoshi
Last active November 17, 2020 15:32
Show Gist options
  • Save ttsukagoshi/8a91a5e2e5e2b3adfaea245cec7855a9 to your computer and use it in GitHub Desktop.
Save ttsukagoshi/8a91a5e2e5e2b3adfaea245cec7855a9 to your computer and use it in GitHub Desktop.
Framework to include localized messages into Google Apps Scripts

How to Use

  1. Prepare a copy of the code in the localized-message.js, setting MESSAGES to suit your needs.
  2. To call a message,
// Get user locale
var locale = Session.getActiveUserLocale();

or alternatively, if you are creating a script bound to a Google Docs file (e.g., a Google Sheets file),

var locale = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetLocale();

Then create an object of the message in that locale

var localizedMessages = new LocalizedMessage(locale);

When calling a message,

console.log(localizedMessages.messageList.{{messageName}})
// Set messages in their respective language as a global object.
const MESSAGES = {
'en_US': {
'messageName': 'messageContent in English'
},
'ja': {
'messageName': '日本語のmessageContent'
}
};
// Class to call the list of localized messages
class LocalizedMessage {
constructor(userLocale = 'en_US') {
this.locale = (MESSAGES[userLocale] ? userLocale : 'en_US');
this.messageList = MESSAGES[this.locale];
Object.keys(MESSAGES.en_US).forEach(key => {
if (!this.messageList[key]) {
this.messageList[key] = MESSAGES.en_US[key];
}
});
}
/**
* Replace placeholder values in the designated text. String.prototype.replace() is executed using regular expressions with the 'global' flag on.
* @param {string} text
* @param {array} placeholderValues Array of objects containing a placeholder string expressed in regular expression and its corresponding value.
* @returns {string} The replaced text.
*/
replacePlaceholders_(text, placeholderValues = []) {
return placeholderValues.reduce((acc, cur) => acc.replace(new RegExp(cur.regexp, 'g'), cur.value), text);
}
/**
* Replace placeholder string in this.messageList.hogefuga
* @param {*} var1
* @param {*} var2
* @returns {string} The replaced text.
*/
replaceHogefuga(var1, var2) {
let text = this.messageList.hogefuga;
let placeholderValues = [
{
'regexp': '\{\{var1\}\}',
'value': var1
},
{
'regexp': '\{\{var2\}\}',
'value': var2
}
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment