Nodejs中hoganjs如何include别的hjs文件呢

Nodejs中hoganjs如何include别的hjs文件呢

在views文件夹里有如下文件 index.hjs index_form.js 在index.hjs中有{{> index_form}} 路由中当访问/时res.render(‘index’); 但浏览器并没有显示index_form中的内容。这是为什么呢? 我也google了,但出来的方法都不行,index_form.hjs无法include到index.hjs中 。 希望大家帮个忙

2 回复

Nodejs中Hogan.js 如何 Include 别的 .hjs 文件?

在使用 Node.js 和 Hogan.js 进行开发时,有时我们希望在一个模板文件中包含另一个模板文件的内容。在你的例子中,index.hjs 中使用 {{> index_form}} 来尝试包含 index_form.hjs 的内容,但实际上没有成功。

问题分析

在 Hogan.js 中,{{> partial}} 语法用于包含部分模板(partial)。但是,如果你遇到问题,可能是因为以下几个原因:

  1. 文件名错误:确保 index_form.hjs 文件存在,并且路径正确。
  2. Hogan.js 版本:确保你使用的 Hogan.js 版本支持 {{> partial}} 语法。
  3. 渲染逻辑:确保你在渲染主模板时正确地包含了部分模板。

示例代码

假设你的目录结构如下:

views/
├── index.hjs
└── index_form.hjs

index.hjs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index Page</title>
</head>
<body>
    <h1>Welcome to the Index Page</h1>
    {{> index_form}}
</body>
</html>

index_form.hjs

<form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <button type="submit">Submit</button>
</form>

路由代码

确保你在路由中正确地渲染了主模板:

const express = require('express');
const hogan = require('hogan.js');
const fs = require('fs');

const app = express();

app.engine('hjs', (filePath, options, callback) => {
    fs.readFile(filePath, 'utf8', (err, source) => {
        if (err) return callback(err);
        const template = hogan.compile(source);
        const rendered = template.render(options);
        callback(null, rendered);
    });
});

app.set('view engine', 'hjs');
app.set('views', './views');

app.get('/', (req, res) => {
    res.render('index', { /* 传递给模板的数据 */ });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

注意事项

  1. 路径问题:确保 views 目录下的文件路径正确。
  2. Hogan.js 引擎配置:你需要自定义一个 Hogan.js 引擎来处理 .hjs 文件的渲染。
  3. 数据传递:如果 index_form.hjs 需要一些动态数据,可以在 res.render 中传递这些数据。

通过以上步骤,你应该能够成功地将 index_form.hjs 包含到 index.hjs 中。如果仍然有问题,请检查控制台输出的错误信息以进一步排查。


Hogan.js 本身并不支持直接的 include 功能,因此你需要自己实现一个辅助函数来处理这种情况。你可以使用 Hogan.js 的部分功能或者通过自定义的方式来实现文件的包含。

以下是一个简单的示例,展示如何通过自定义逻辑将 index_form.hjs 包含到 index.hjs 中:

示例

假设目录结构如下:

/views
    /index.hjs
    /index_form.hjs

1. index.hjs 文件

<!DOCTYPE html>
<html>
<head>
    <title>Index Page</title>
</head>
<body>
    <div class="main-content">
        {{> index_form}}
    </div>
</body>
</html>

2. index_form.hjs 文件

<p>This is the form content.</p>

3. Node.js 路由代码

在路由中,你需要读取 index_form.hjs 文件的内容并将其插入到 index.hjs 中。

const express = require('express');
const hogan = require('hogan.js');
const fs = require('fs');
const path = require('path');

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

app.get('/', (req, res) => {
    // 读取 index.hjs 和 index_form.hjs 文件
    const indexTemplatePath = path.join(app.get('views'), 'index.hjs');
    const formTemplatePath = path.join(app.get('views'), 'index_form.hjs');

    fs.readFile(indexTemplatePath, 'utf8', (err, indexContent) => {
        if (err) return res.status(500).send('Error reading index template.');
        
        fs.readFile(formTemplatePath, 'utf8', (err, formContent) => {
            if (err) return res.status(500).send('Error reading form template.');

            // 编译模板
            const compiledIndexTemplate = hogan.compile(indexContent);
            const compiledFormTemplate = hogan.compile(formContent);

            // 渲染表单内容
            const formHtml = compiledFormTemplate.render();

            // 替换 {{> index_form}} 占位符
            const finalHtml = indexContent.replace('{{> index_form}}', formHtml);

            // 渲染最终的 HTML
            res.send(finalHtml);
        });
    });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

解释

在这个示例中,我们首先读取 index.hjsindex_form.hjs 文件的内容,然后分别编译这两个模板。接着,我们将 index_form.hjs 模板渲染为 HTML 字符串,并将其替换 index.hjs 中的 {{> index_form}} 占位符。最后,我们将最终的 HTML 发送到客户端。

这种方法虽然有点绕,但可以实现你的需求。如果需要更复杂的逻辑或更多的模板文件,可以考虑使用其他模板引擎(如 EJS、Pug 等),它们通常提供了更强大的功能,如内置的 includeextend 功能。

回到顶部