【问题标题】:Mustache does not render values, when deployed部署时,Mustache 不呈现值
【发布时间】:2018-02-16 00:44:52
【问题描述】:

节点版本:v8.9.0;

我使用 mustache 从模板中渲染一些 html,如下所示:

static createHtml(title, variables, template) {
  let header = fs.readFileSync(headerPath);
  let content = fs.readFileSync(contentPath);
  let footer = fs.readFileSync(footerPath);

  var headerVars = {
    title: title
  };

  console.log('createHtml: ', variables); // <- variables are as expected

  try {
    header = Mustache.render(header.toString(), headerVars);
    content = Mustache.render(content.toString(), variables);
  } catch (e) {
    console.log('Moustache error:\n', e); // <- no error is thrown
  }

  const html = header + content + footer;

  console.log('content', content); // <- content does not include filled variables when deployed

  return html;
}

当我在本地机器上运行它时,一切正常,但是当它被部署时,变量并没有注入到模板中。我有几个假设,并试图找出环境与本地环境不同的所有可能方式,但到目前为止没有任何效果。它在 EC2 上部署到 AMI Linux 实例。

任何想法,我怎么能弄清楚有什么区别?根据控制台日志,它一定是 Mustache.render() 中的东西。

【问题讨论】:

    标签: node.js templates mustache


    【解决方案1】:

    似乎 AMI Linux 上部署的实例在某一点之后并不真正喜欢同步 fs.readFileSync 操作(重点是什么,为什么仍然是悬而未决的问题),尽管解决方案非常简单。只需将代码重构为 async 如下:

    static createHtml(title, variables, template) {
      fs.readFile(headerPath, (err, header) => {
        fs.readFile(contentPath, (err, content) => {
          fs.readFile(footerPath, (err, footer) => {
    
            var headerVars = { title: title };
    
            header = Mustache.render(header.toString(), headerVars);
            content = Mustache.render(content.toString(), variables);
    
            const html = header + content + footer.toString();
    
            return html;
          });
        });
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 2023-03-19
      • 2012-03-23
      相关资源
      最近更新 更多