Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import i18n from "i18next";
- import { initReactI18next } from "react-i18next";
- import moment from "moment";
- import en from "./en";
- import dk from "./dk";
- i18n
- .use(initReactI18next) // passes i18n down to react-i18next
- .init({
- resources: {
- en,
- dk
- },
- lng: "en",
- fallbackLng: "en",
- keySeparator: false, // we do not use keys in form messages.welcome
- interpolation: {
- escapeValue: false, // react already safes from xss
- // parse format string, it should match the following pattern
- // {{value, formatter, key1 = value1, key2 = value2, keyN = valueN}}
- format(value, format, lng) {
- const parts = format.split(",");
- const formatterName = parts.shift();
- const params = parts
- .map(x => x.split("=").map(y => y.trim()))
- .reduce((obj, pair) => {
- if (pair.length > 1) {
- obj[pair[0]] = pair[1];
- } else {
- obj[pair[0]] = pair[0];
- }
- return obj;
- }, {});
- const formatter = formatters[formatterName];
- if (formatter) {
- return formatter(value, params, parts.join(","), lng);
- }
- return value;
- }
- }
- });
- export default i18n;
- const formatters = {
- /**
- * date formatter
- * @param value
- * @param params
- * @param format
- * @return {string}
- */
- date(value, params, format) {
- switch (value) {
- case "now":
- value = moment();
- break;
- case "yesterday":
- value = moment().add(-1, "d");
- break;
- case "tomorrow":
- value = moment().add(1, "d");
- break;
- }
- return moment(value).format(format);
- },
- /**
- * amount formatter
- * @param value
- * @param zero
- * @param many
- * @param others
- * @return {string}
- */
- amount(value, { zero, many, others }) {
- if (!value && zero) return i18n.t(zero);
- if (value > 1 && many) return i18n.t(many, { value });
- return i18n.t(others, { value });
- },
- /**
- * list formatter
- * @param list list of string
- * @param empty indicate the text to display if no item
- * @param others indicate the text to display for the rest of items
- * @param x indicate first items should be display (default = 1)
- * @param sep indicate list item separator (default = comma)
- * @return {string|string | *|*}
- *
- * Samples:
- * users = ['user1', 'user2', 'user3']
- * {{users, list, empty=noUser, others=otherUsers, x=2}}
- * noUser: No user
- * otherUsers: and {{count}} other(s)
- * output: user1, user2 and 1 other(s)
- */
- list(list, { empty, others, x = 1, sep = "," }) {
- // show empty text if list is empty
- if (!list || !list.length) return i18n.t(empty);
- // show first item value if list has only one item
- if (list.length === 1) return list[0];
- // show first x item values if list has more than x items
- return (
- list.slice(0, x).join(sep) + i18n.t(others, { count: list.length - 1 })
- );
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement