import {isArray} from "@/utils/validate"; /** * 根据模板生成字符串 * @param data 数据 * @param template 模板 * @returns 字符串 */ export function formatStringByTemplate(data: any, template: string) { let result = template if (data) { if (isArray(data)) { if (data.length === 0) { return result; } // 数组 return formatStringByList(data, result); } else { return replaceText(result, data); } } return result; } /** * [[{{姓名}}任{{职务}},负责{{工作职责}}]] * @param data * @param template * @returns {*} */ function formatStringByList(list: any[], template: string) { let result = template const regex = /\[\[.*?\]\]/g let templates = result.match(regex) const keys = Object.keys(list[0]); const templatess: any[] = [] templates?.forEach(t => { let temp = t.substring(2, t.length - 2); let temps: any[] = [] list.forEach(d => temps.push(replaceText(temp, d))) let ts = temps.join(';'); if (ts.length > 0 && !ts.endsWith('。')) { ts = ts + '。' } templatess.push(ts) }) templates?.forEach((ts, index) => { result = result.replace(ts, templatess[index]) }) return result; } function replaceText2(template: string, data: { [key: string]: any }) { const keys = Object.keys(data); keys.forEach(key => { template = template.replace(new RegExp('{{' + key + '}}', 'g'), data[key] || ''); }); return template; } function replaceText(template: string, data: any) { // 正则表达式,用于匹配{{key}},包括可能存在的空格 const regex = /{{\s*([^}]+?)\s*}}/g; // 递归函数,用于处理嵌套对象 function replaceValue(key: string) { // 分割键名,以处理嵌套对象 const keys = key.split('.'); let value = data; for (const k of keys) { // 如果值为undefined或null,则停止查找 if (value === undefined || value === null) break; value = value[k]; } // 如果找到的值是undefined或null,则替换为空字符串 return value === undefined || value === null ? '' : value; } // 使用正则表达式替换模板中的所有匹配项 return template.replace(regex, (match, key) => replaceValue(key)); }