A
A
angelzzz2018-09-25 15:31:28
Node.js
angelzzz, 2018-09-25 15:31:28

How to use source in handlebars from external file and not from inline code (to add css, js and change title)?

Very strange that this is not included in the documentation. At least I couldn't find it.
There is a standard pattern for using handlebars :

var source = "<p>Hello, my name is {{name}}. I've uploaded {{number}} of photo(s)</p>" +
  "<div>{{#each element}}" +
  "<p><img src='{{ this }}'></p>" +
  "{{/each}}</div>";

  var template = handlebars.compile(source);
  var html = template(data);
  console.log(html);

Is it possible to use a file together inline in source. Something along the lines of:
var source = require('./template.html')

var template = handlebars.compile(source);
var html = template(data);
console.log(html);

And inside template.html have the following code:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>{{title}}</title>
  <link rel="stylesheet" media="all" href="/somefile.css">
  <script type="text/javascript" src="/somefile.js"></script>
</head>
<body>
  <h1 class="h1-like">{{sometext}}</h1>
  <p>{{somepara}}</p>
</body>
</html>

As you can see from the example, I need to generate approximately the same html files using Nodejs from the data that I receive from the database.
PS Or maybe there is another template engine that allows you to do this simply?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-09-25
@angelzzz

You can do this:

var fs = require('fs');

var source = fs.readFileSync('./template.html', 'utf8');

var template = handlebars.compile(source);
var html = template(data);
console.log(html);

Also, it would be a good idea to do it asynchronously:
var fs = require('fs');

fs.readFile('./template.html', 'utf8', function(err, source) {
  var template = handlebars.compile(source);
  var html = template(data);
  console.log(html);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question