Is it wrong to use Swig with node.js in this way? If yes - why?
Please let me know if additional information needed to answer the question.
If it possible, please add links or/and examples of code that can help to understand the answer.
Current code works and makes what I want, but there is feeling that something (or everything:)) wrong here.
Here how my files looks like:
views/block-header.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
views/block-footer.html
</body>
</html>
views/layout-home.html
{{HEADER_tpl|safe}}
<h1>Some heading</h1>
<div>Layout home</div>
{{FOOTER_tpl|safe}}
controllers/home.js
var swig = require('swig');
var layout_home_tpl = swig.compileFile('views/layout-home.html');
var block_header_tpl = swig.compileFile('views/block-header.html');
var block_footer_tpl = swig.compileFile('views/block-footer.html');
var mainPageOutput = layout_home_tpl({
HEADER_tpl: block_header_tpl(),
FOOTER_tpl: block_footer_tpl()
});
exports.get = function( request, response ){
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(mainPageOutput);
response.end();
};
Thanks in advance for your time.
It's not "wrong", but it's definitely not a typical usage. The preferred way would be to use the built-in template inheritance:
views/home.html
{% extends "layout/basic.html" %}
{% block content %}
<h1>Some heading</h1>
<div>Layout home</div>
{% endblock %}
views/basic.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
controllers/home.js
var swig = require('swig');
exports.get = function( request, response ){
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(swig.renderFile('views/home.html'));
response.end();
};