gpt4 book ai didi

HTML 文件作为 Node.js 中的变量

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:31 25 4
gpt4 key购买 nike

我需要使用简单的 Node.js 服务器通过电子邮件以 html 形式发送某些内容(我正在使用 Sendgrid)。我只是发送一些带有变量和换行符的文本。

var postData = 'lat: ' + formatted.latitude + '<br>lng: ' + formatted.longitude + '<br>time: ' + formattedDate;
sendEmail(postData);

然后我使用 Sendgrid 以 HTML 格式发送电子邮件。

var content = new helper.Content('text/html', messageContent);

无需粘贴剩余的代码块。

我需要的是更复杂的 .html 文件,其中包含 css 和 javascript。此外,我需要更改其中的一些值。将此文件分配给变量并像这样发送它的最简单方法是什么?

最佳答案

不确定我是否理解这个问题,但您可以非常简单地阅读该文件。只是

var fs = require('fs'); //Filesystem    

var content = fs.readFileSync("path/to/File/file.html","utf-8");
//this is the content of your file.html

如果你保持简单,你可以只使用一种正则表达式并用值替换某些内容。如果它必须更复杂,我建议你使用模板引擎。我个人的偏好是mustache 。Mustache 还有一个 Nodejs 库,名为 Mustache 。在这种情况下,您可以像这样使用它:

const mustache   = require('mustache');
const fs = require('fs'); //Filesystem
//...
var content = fs.readFileSync("path/to/File/file.html","utf-8");
var view = {formatted:{latitude: 0,longitude:0}, formattedDate:"01/01/1990"}
var output = mustache.render(content, view);

为此,您必须首先了解 Mustache,但这非常简单。查看教程here

您的file.html应该如下所示:

<div> lat: {{formatted.latitude}} <br> lng: {{formatted.longitude}} </div>
<script>
var formattedDate = "{{formattedDate}}";
</script>

请注意,您必须安装 Mustache npm install Mustache 首先

关于HTML 文件作为 Node.js 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43804188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com