如何统一.pug和节点文件

时间:2019-04-10 14:18:49

标签: node.js pug

我是帕格(玉)的新人。 我有以下标记,正是我想要的html部分:

doctype html
html(lang="en")
  head
    title= "Project BOT"
  body
    h1 My project BOT
    .container
      .row
        - for (var i=0; i<5; i++){
          .item col-md-3 col-sm-12 #content
            .card
              .front
                p.telegram_id
                p.restaurant_name
                p.discount
                p.timestamp
                button
                .back
          - }

我有一个nodejs文件,可在其中建立与数据库的连接并仅输出数据库内容。看起来如下:

// mysql connection credentials
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'host',
    user: 'user',
    password: 'pass',
    database: 'dbname'
});

// connect to database
connection.connect(function (err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
    console.log('connected as id ' + connection.threadId);
});

connection.query('SELECT * from botrequests',
  function (error, results, fields) {
    if (error) throw error;
      console.log(results);
});

我想做的是在哈巴狗的for循环中输出数据库字段。什么是正确的(或可能的)方法? 循环看起来像:

- for (var i=0; i<results.length; i++){
          .item col-md-3 col-sm-12 #content
            .card
              .front
                p.telegram_id results[i].id
                p.restaurant_name results[i].name
                p.discount results[i].discount
                p.timestamp results[i].time
                button
                .back
          - }

谢谢!

1 个答案:

答案 0 :(得分:1)

使用express的简单服务器:

var express = require('express');
var app = express();

app.set("view engine","jade")

app.get('/', function (req, res) {


    // mysql connection credentials
    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'host',
        user: 'user',
        password: 'pass',
        database: 'dbname'
    });


    // connect to database
    connection.connect(function (err) {
        if (err) {
            return err;
        }
        console.log('connected as id ' + connection.threadId);

        connection.query('SELECT * from botrequests',
          function (error, results, fields) {
            if (error) throw error;

            res.render('JadeFileName', { results: results });
        });

    });

});

然后玉可以在内部循环遍历所有项目:

if results && results.length
  each r in results
    .item col-md-3 col-sm-12 #content
      .card
        .front
          p.telegram_id #{r.id}
          p.restaurant_name #{r.name}
          p.discount #{r.discount}
          p.timestamp #{r.time}
          button
          .back