【发布时间】:2021-01-14 05:19:38
【问题描述】:
我正在研究本网站提出的解决方案: https://jeffreyeverhart.com/2020/09/29/auto-fill-a-google-doc-template-from-google-sheet-data/ 特别是我对用电子表格中的数据替换标记很感兴趣。
但我想要一个更灵活的解决方案。在此示例中,标记是在代码中定义的:
//In these lines, we replace our replacement tokens with values from our spreadsheet row
body.replaceText('{{First Name}}', row[0]);
body.replaceText('{{Last Name}}', row[1]);
body.replaceText('{{Position}}', row[2]);
我希望电子表格中的所有可用标记都将被替换。例如,在此解决方案中适用于 gmail 模板: https://developers.google.com/gsuite/solutions/mail-merge
function fillInTemplateFromObject_(template, data) {
// we have two templates one for plain text and the html body
// stringifing the object means we can do a global replace
let template_string = JSON.stringify(template);
// token replacement
template_string = template_string.replace(/{{[^{}]+}}/g, key => {
return escapeData_(data[key.replace(/[{}]+/g, "")]) || "";
});
return JSON.parse(template_string);
};
/**
* Escape cell data to make JSON safe
* @see https://stackoverflow.com/a/9204218/1027723
* @param {string} str to escape JSON special characters from
* @return {string} escaped string
*/
function escapeData_(str) {
return str
.replace(/[\\]/g, '\\\\')
.replace(/[\"]/g, '\\\"')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t');
};
谢谢
【问题讨论】:
-
你有什么问题?
-
基本上我想用类似 template_string.replace(/{{[^{}]+}}/g, key => { return escapeData_(data [key.replace(/[{}]+/g, "")]) || ""; 用在第二个例子中
-
是什么阻止你这样做?
-
因为在谷歌文档中我试过 .getBody().replace(/{{[^{}]+}}/g, key => { return escapeData_(data[key.replace(/[ {}]+/g, "")]) || ""; 和 .getBody().replaceText(/{{[^{}]+}}/g, key => { return escapeData_(data[key.替换(/[{}]+/g, "")]) || ""; 但不起作用
-
阅读下面的答案我认为这就是你的答案。