【问题标题】:Appending extra elements to existing string of html in Node.js在 Node.js 中将额外元素附加到现有的 html 字符串
【发布时间】:2017-11-06 17:16:47
【问题描述】:

我需要在 Node.js 中动态地将页眉和页脚附加到 HTML 网页的特定元素,但我不知道该怎么做。我有一个函数,它将 html 作为字符串和选项,这些选项可能包含也可能不包含用于页眉和页脚内容的额外字符串。

这个想法是,如果将页眉或页脚传递到函数中,它将被适当地附加到现有的 HTML 中。

这是函数的样子。我正在使用 lodash 来测试是否有页眉/页脚内容。我想在 if 块内执行追加。我看过cheerio,但不确定是否可以在字符串中使用它。提前感谢您的帮助!

function generator(html, options) {

    var header = _.get(options, 'partials.header');
    var footer = _.get(options, 'partials.footer');


  // Check if either header of footer options.partials
    if(header || footer) {
      console.log('YEAH! ::: ', header);
      // Append header and/or footer to the HTML here

    }
}

【问题讨论】:

标签: javascript html node.js dom-manipulation


【解决方案1】:

如何连接字符串?

function generator(html, options) {

    var header = _.get(options, 'partials.header') || '';
    var footer = _.get(options, 'partials.footer') || '';


    // Check if either header of footer options.partials
    if (header || footer) {
      html = (header + html + footer);
    }

    return html;
}

【讨论】:

  • 感谢您的建议,在这种情况下效果很好。问题是页眉和页脚必须在 html 中,这是一个完整的网页,并且在特定点处附加。例如,标题应作为页面包装器 div 的直接子节点附加。对不起,我没有说得更清楚。
  • @mikeym 在 html 中添加占位符,然后使用正则表达式在这些点交换页眉/页脚怎么样?
猜你喜欢
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多