Is it wrong to use the Swig templating pattern in node.js?
Is it wrong to use Swig with node.js this way? If so, why?
Please let me know if you need more information to answer the question.
If possible, add links and / or code examples that might help you understand the answer.
The current code works and does what I want, but there is a feeling that something (or everything :)) is wrong here.
This is what my files look like:
view / block-header.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
view / block-footer.html
</body>
</html>
view / 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.
+3
source to share
1 answer
It's not "wrong", but it's definitely not typical use. The preferred way would be to use inline template inheritance :
view /home.html
{% extends "layout/basic.html" %}
{% block content %}
<h1>Some heading</h1>
<div>Layout home</div>
{% endblock %}
view /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();
};
+11
source to share