html - Node.js SWIG 支持异步功能吗?

标签 html node.js swig-template

我有使用 Node.js 和 SWIG 模板引擎的动态 html 页面。我需要从 SWIG 模板调用函数来从数据库获取用户数据以呈现页面内容。 SWIG 调用函数但不等待数据库的响应。 那么,是否可以调用异步函数并将数据返回到 swig 模板?

我的 SWIG 模板:todos.html

<body>
{%set todos=getTodos()%}
{%for item in todos%}
  <div>{{item.name}}</div>
  <div>{{item.completed}}</div>
{%endfor%}

</body>

我的 Node 服务器(使用express):

.......
swig.setDefaults({locals:{getTodos:function(input){
       setTimeout(function(){
        return [
                {name:"First todo",completed:false},
                {name:"Same name",completed:true},
               ]
       },5000)
    })
........

但是页面渲染时没有等待来自“超时”的数据。

最佳答案

所以基本上不行,你不能直接在模板中使用异步函数。不支持。

但是您仍然可以通过首先异步获取所需的所有数据,然后渲染 swig 模板来完成您想要的操作。

这是一个最小的例子:

const swig = require('swig');
const express = require('express');

const app = express();

const swigEngine = new swig.Swig();
app.engine('html', swigEngine.renderFile);
app.set('view engine', 'html');

const loadTodos = function (callback) {
    setTimeout(function () {
        const todos = [
            {name: "First todo", completed: false},
            {name: "Same name", completed: true},
        ];

        callback(null, todos);
    }, 1000)
};

app.get('/', (req, res) => {
    // So first you get the data asynchronously 
    loadTodos(function (err, data) {
        if (err) {
            res.sendStatus(400);
            return;
        }
        
        res.render('index', {todos: data});
    })
});

app.listen(5555, () => console.log('Server is running on port 5555.'))

如果你这样做,你的模板也会变得更加简单:

{%for item in todos%}
	<!-- You have missed the curly brackets here {{}} -->
	<div>{{item.name}}</div>
	<div>{{item.completed}}</div>
{%endfor%}

关于html - Node.js SWIG 支持异步功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47955502/

相关文章:

jquery - 切换图标不改变 html css jquery

c++ - <Swig 类型为 'std::map< char,int > 的对象的代理

c# - 使用 SWIG 更改生成的 CS 函数中的返回类型

node.js - 如何使用 Express 4 渲染 Swig 模板?

php - 在html表格中打印数据库数据

javascript - 在固定高度内显示尽可能多的文本

javascript - 如何在单击 <a> 标签时关闭汉堡包导航?

javascript - Node.js 不同函数之间的全局变量

jquery - 我的导航菜单有问题。我正在使用 Bootstrap 3、JQuery 2.3.1、Jade、ExpressJS 和 Node.js

javascript - 我应该为我的单页应用程序使用 node.js 吗?