简体   繁体   English

从Node.js中的模板写入文件

[英]Write file from a template in Node.js

I want to generate a file from a template. 我想从模板生成一个文件。 For example, I have a handlebars (but it can be another template) like this 例如,我有一个把手(但它可以是另一个模板),就像这样

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

Then, I make a query to the database, and return the view to the browser. 然后,我对数据库进行查询,并将视图返回给浏览器。 But now, I dont want return the view, but save it as a file on the server disk. 但是现在,我不希望返回视图,而是将其保存为服务器磁盘上的文件。 How can I do it? 我该怎么做?

I try generate and save from the browser, but I want do the proccess in the server 我尝试从浏览器生成并保存,但我想在服务器中执行proccess

You have to "compile" the template manually and write the result into the respective file. 您必须手动“编译”模板并将结果写入相应的文件。 Like: 喜欢:

const fs = require('fs');
const Handlebars = require('handlebars');

const source = '<div>{{title}}</div>';
const template = Handlebars.compile(source);

const contents = template({title: 'Wohooo!'});

fs.writeFile('contents.html', contents, err => {
    if (err) {
        return console.error(`Autsch! Failed to store template: ${err.message}.`);
    }

    console.log(`Saved template!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM