choerodon-ui
Version:
An enterprise-class UI design language and React-based implementation
62 lines (49 loc) • 1.76 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import { createElement, Fragment, isValidElement } from 'react';
import format from 'string-template';
import isString from 'lodash/isString';
import isObject from 'lodash/isObject';
import isNil from 'lodash/isNil';
import flatMap from 'lodash/flatMap';
export default function formatReactTemplate(template, map) {
var result = [template];
Object.keys(map).forEach(function (key) {
var node = map[key];
if (!isNil(node)) {
result = flatMap(result, function (text) {
if (isString(text)) {
var stringText = text;
if (isValidElement(node)) {
var placeholder = "{".concat(key, "}");
if (isObject(node) && stringText.indexOf('[object Object]') > -1) {
placeholder = '[object Object]';
}
var _placeholder = placeholder,
length = _placeholder.length;
var textArr = [];
var index = stringText.indexOf(placeholder);
while (index > -1) {
if (index > 0) {
textArr.push(stringText.slice(0, index));
}
textArr.push(node);
stringText = stringText.slice(index + length);
index = stringText.indexOf(placeholder);
}
if (stringText) {
textArr.push(stringText);
}
return textArr;
}
return format(text, map);
}
return text;
});
}
});
if (result.every(isString)) {
return result.join('');
}
return createElement.apply(void 0, [Fragment, {}].concat(_toConsumableArray(result)));
}
//# sourceMappingURL=formatReactTemplate.js.map