【问题标题】:Display variable from JS file in html using pug file [duplicate]使用pug文件在html中显示来自JS文件的变量[重复]
【发布时间】:2019-05-05 11:58:53
【问题描述】:

我有两个文件。一个是pug文件:

doctype html
html
head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
    link(href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', rel='stylesheet')
    title Your first page
body
    script(src='https://code.jquery.com/jquery-3.3.1.min.js')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js')
    script(src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js')

第二个是JS文件:

var express = require('express'),
    logger = require('morgan');
var app = express();
var x = 1;
var y = 2;
 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'pug');         
app.use(logger('dev'));                        
app.use(express.static(__dirname + '/public')); 
 
app.get('/', function (req, res) {      
    res.render('index', {pretty:true}); 
});
 
app.listen(3000, function () {                  
    console.log('The application is available on port 3000');
});

现在我想使用 x 和 y 变量并使用 pug 文件显示它们。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript node.js pug


    【解决方案1】:

    试试这个。

    1. 将变量传递给您的视图
    app.get('/', function (req,res) { 
        res.render('index', { pretty: true, title: 'Hey', message: 'Hello there!'}); 
    });
    
    1. 然后在“/public/views”中的模板文件“index.pug”中回显
    doctype html
    html
    head
        meta(charset='utf-8')
        meta(name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
        link(href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', rel='stylesheet')
        title Your first page
        title= title
    body
        script(src='https://code.jquery.com/jquery-3.3.1.min.js')
        script(src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js')
        script(src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js')
    
        h1=message
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      在您的代码中,您已经将一个变量传递给模板 (pug)。你也可以这样做:

      app.get('/', function (req, res) {      
         res.render('index', {pretty:true, x: x, y: y}); 
      });
      

      x: 是“键”,x 是对变量 x 的引用。与 y 的过程相同。

      在您的哈巴狗文件中,例如:

      h1 = x
      h2 = y
      

      希望能帮到你。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多