简体   繁体   English

如何在 Nodejs 服务器上使用 Handlebars 呈现静态 HTML 文件?

[英]How can I render a static HTML file with Handlebars on a Nodejs server?

I have come across plenty of resources online for this but haven't been able to find one that is straight forward enough for me to understand.为此,我在网上找到了大量资源,但无法找到足够直接让我理解的资源。

At the moment, I have multiple massive <script> tags in an HTML document that has handlebars content.目前,我在一个包含把手内容的 HTML 文档中有多个大量的<script>标签。 The server sends this HTML document to the client where the client then renders the page with data from an AJAX call.服务器将此 HTML 文档发送到客户端,然后客户端使用来自 AJAX 调用的数据呈现页面。 I'd like to move this entire process server-side so that all the server has to do is send a static file and re-render the page when data is updated.我想将整个流程移动到服务器端,以便服务器所要做的就是发送一个静态文件并在数据更新时重新呈现页面。 Data changes a few times per day - which is why it isn't hard coded in and I would like to run the handlebars compiler on the HTML document when data is updated.数据每天更改几次 - 这就是为什么它不是硬编码的原因,我想在更新数据时在 HTML 文档上运行把手编译器。

Is it possible to simply put the HTML document with handlebars templating in <script> tags through a function to generate a new HTML file with data filled in?是否可以通过函数简单地将带有把手模板的 HTML 文档放在<script>标签中,以生成一个填充了数据的新 HTML 文件?

Here is the code I have within my app.js file that is runned the Node server that does not do what I want it to:这是我的app.js文件中的代码,该文件在 Node 服务器上运行,但不执行我想要的操作:

function registerHelpers(callback){
  Handlebars.registerHelper('equal', function(lvalue, rvalue, options) {
    if (arguments.length < 3)
        throw new Error("Handlebars Helper equal needs 2 parameters");
    if( lvalue!=rvalue ) {
        return options.inverse(this);
    } else {
        return options.fn(this);
    }

  });

  Handlebars.registerHelper('trim', function(text) {
    text = text.replace(/ /g, '');
    return new Handlebars.SafeString(text);
  });

  callback();
}

function buildHomePage() {
  var source = require(__dirname + '/public/home.handlebars');
  var template = Handlebars.precompile(source);
  var collection = db.get('datalist'); //Monk call to MongoDB
  collection.find({}, function (err, docs){
    var result = template(docs);
    console.log(result)
    var fs = require('fs');
        fs.writeFile("test.html", result, function(err) {
        if(err) {
          console.log(err);
        }
    });
  });
};

registerHelpers(buildHomePage);

The following can render handlebars to static html.以下可以将车把渲染为静态 html。 Run node example.js .运行节点example.js You may need to run npm install --save handlebars prior.您可能需要先运行npm install --save handlebars

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

function render(filename, data)
{
  var source   = fs.readFileSync(filename,'utf8').toString();
  var template = Handlebars.compile(source);
  var output = template(data);
  return output;
}

var data = JSON.parse(fs.readFileSync("./data/strings.json", 'utf8'));

var result = render('./templates/somefile.html', data);

console.log(result);

If your handlebars templates are simple, with only string replacement, you can do this with underscore.js.如果您的车把模板很简单,只有字符串替换,您可以使用 underscore.js 来实现。 Assume this example is named 'generate.js'假设这个例子被命名为“generate.js”

var fs = require('fs');
var _ = require('underscore');
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

function render(filename, data)
{
  var source   = fs.readFileSync(filename,'utf8').toString();
  var compiled = _.template(source);
  return compiled(data);
}

var data = JSON.parse(fs.readFileSync("./data/strings.json", 'utf8'));

var result = render('./templates/somefile.html', data);

console.log(result);

Then run node generate.js to output the rendered template to the console.然后运行node generate.js将渲染的模板输出到控制台。 You may need to do npm install --save underscore prior.您可能需要先执行npm install --save underscore

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

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