如何使用Node + Express呈现多个视图 [英] How to render multiple views using Node+Express

查看:60
本文介绍了如何使用Node + Express呈现多个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个header.html和footer.html,我希望它们与其他视图一起呈现.我想使用Node + Express完成此操作. 我尝试通过以下方式呈现视图,但显然不起作用:

I have a header.html and a footer.html which I would like to be rendered along with other views. I want to accomplish this using Node+Express. I tried to render views in the following way but clearly it doesn't work:

var express = require('express');
var app = express();
app.get('/', function(req, res) {
    res.render('header');
    res.render('home');
    res.render('footer');
});

推荐答案

您必须为项目设置模板引擎. 例如,您可以使用 Swig ,它的效果非常好,并且有据可查.

You have to set a template engine to your project. You can use Swig for instance, it works very nice and it is well documented.

下面的示例向您展示如何设置它以及如何从布局或母版页调用部分视图.

The example below, shows you how to set it and how you can call partial views from a layout or master page.

通过在项目根目录上执行npm install swig --save进行安装. 您需要安装一个称为consolidate的附加库,该库充当不同模板引擎库之间的接口,这是快速应用程序中的一种标准.

Install it by doing npm install swig --save on your project root. You need to install an additional library called consolidate which acts as interface among different template engine libraries, it is kind of standard in express applications.

npm install consolidate --save

使用

consolidate = require('consolidate');
swig = require('swig');

配置如下:

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views'); // set your view path correctly here

然后,您可以将页面呈现为:

Then you can render a page as:

app.get('/', function (req, res) {
  res.render('index', {});
});

(示例取自Swig的作者Paul Armstrong github页面) Layout.html:

(Example taken from Swig's author, Paul Armstrong github page) Layout.html:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>{% block title %}{% endblock %} - Example</title>
</head>
<body>
    <header>
        <h1>{% block title %}{% endblock %}</h1>
        {% block header %}{% endblock %}
        <nav>
            <ul>
                <li><a href="/">Home Page</a></li>
                <li><a href="/people">People</a></li>
            </ul>
        </nav>
    </header>

    <section role="main">
        {% block body %}{% endblock %}
    </section>

</body>
</html>

Index.html:

Index.html:

{% extends 'layout.html' %}

{% block title %}Home Page{% endblock %}

这样,您可以根据需要将视图分离:)

This way, you can decoupled your views as you need :)

这篇关于如何使用Node + Express呈现多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆