3

以这种方式将 Swig 与 node.js 一起使用是错误的吗?如果是 - 为什么?

如果需要其他信息来回答问题,请告诉我。

如果可能,请添加有助于理解答案的链接或/和代码示例。

当前的代码可以工作并且可以实现我想要的,但是感觉这里的某些东西(或所有东西:))是错误的。

我的文件如下所示:

意见/block-header.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

意见/block-footer.html

</body>
</html>

意见/布局-home.html

{{HEADER_tpl|safe}}
<h1>Some heading</h1>
<div>Layout home</div>
{{FOOTER_tpl|safe}}

控制器/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();
};

在此先感谢您的时间。

4

1 回答 1

11

这不是“错误”,但绝对不是典型的用法。首选方法是使用内置模板继承

意见/home.html

{% extends "layout/basic.html" %}

{% block content %}
<h1>Some heading</h1>
<div>Layout home</div>
{% endblock %}

意见/基本.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

控制器/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();
};
于 2014-08-20T22:09:21.363 回答