【问题标题】:Modifying HTML File w/ Node and Dynamically Generated HTML使用节点和动态生成的 HTML 修改 HTML 文件
【发布时间】:2019-11-07 21:19:12
【问题描述】:

我正在编写一个应用程序,该应用程序使用大部分已填写的 HTML 模板,并使用 nodemailer 发送电子邮件。我需要根据我的 webscraper 发生的情况在特定点写入到静态 html 文件中。

节点有一个 id 属性,我称之为“root”或“insert_root”。

        ... MORE HTML ...
<tbody>
   <tr> 
     <td class="pc-fb-font" style="padding: 20px 20px; text-align: center; font-... 
        <div id="insert_root" style="margin-left: 20px"> 
         **Insert Here**
        </div>
     </td>
  </tr>
</tbody>
        ... THE REST OF THE HTML ...

最简单、最可靠的方法是什么?我要插入的 html 内容如下所示:

<p style="margin-bottom: 10px; margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 600; line-height: 1.42; letter-spacing: -0.4px; color: #151515;">Coons, Christopher A:</p>
<ul style="margin-left: 20px; margin-top: 0px; padding: 0px; ">
   <li style="margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 12px; font-weight: 500; line-height: 1.42; letter-spacing: -0.4px; color: #151515;"><a href=https://efdsearch.senate.gov/search/view/ptr/f06ca66b-6f1d-461e-990d-01e6bb206b51/>Periodic Transaction Report for 06/24/2019</a></li>
</ul>
<p style="margin-bottom: 10px; margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 600; line-height: 1.42; letter-spacing: -0.4px; color: #151515;">Roberts, Pat:</p>
<ul style="margin-left: 20px; margin-top: 0px; padding: 0px; ">
   <li style="margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 12px; font-weight: 500; line-height: 1.42; letter-spacing: -0.4px; color: #151515;"><a href=https://efdsearch.senate.gov/search/view/annual/ea3ce82e-f1e0-4f16-8498-79d02398f06c/>Annual Report for CY 2018</a></li>
</ul>

我想我可以做一些事情,我使用 fs.readFile 读取文件并写入它,但想知道是否有更简单的解决方案涉及 Cheerio 或其他 HTML 解析器来获取确切的根节点,并以某种方式从有什么想法?

【问题讨论】:

  • 您的应用程序是否使用任何可以呈现您的变量并返回模板的模板引擎?使用下划线等? _.template().

标签: javascript html node.js dom fs


【解决方案1】:

正如 Lawrence 指出的,我应该使用模板引擎。

我将 和 放在我的 html 文件中以接受文本。代码如下所示(在异步函数中):

const readFile = (fileName) => util.promisify(fs.readFile)(fileName, 'utf8');
const writeFile = (fileName, content) => util.promisify(fs.writeFile)(fileName, content, 'utf8');

let dynamicTtile = "titleIwanttoinsert";
let dynamicPost = "postIwantToInsert"

let html = await readFile(path.resolve(__dirname, "./emailContent/blankHtml/index.html"));

let tmpl = _.template(html);
let newHtml = tmpl({ target: dynamicHtml, targetTitle: dynamicTitle });

await writeFile(path.resolve(__dirname, 'emailContent', 'emails', 'sent', 'index.html'), newHtml);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    相关资源
    最近更新 更多