将 javascript 中的值传递给 jade

Pass values from javascript to jade

我正在使用 node.js、express、jade 和 socket.io,我可以在 jade 端获取 javascript 代码到 运行,但我无法生成html 来自脚本。区块

我必须根据您的意见更新我的问题。以下是文件:

server.js

 app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
      socket.emit('news', { hello: res}); // res is the reponse object
      socket.on('my other event', function (res) {
      console.log("socket.io connected and data sent to jade");
      });
    });

layout.jade:

doctype html
html
  head
    title= title

    script(src='components/jquery/dist/jquery.min.js')

script(type='text/javascript' src='https://cdn.socket.io/socket.io-1.0.6.js')
script(type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/jade.min.js')
script(type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/runtime.min.js')

  script.
  var socket = io.connect('http://localhost:8898/');
  socket.on('news', function (data) {
    var photo = data.hello.data[0].images.original.url;      
  });


body
    block content
      img(src="#{photo}")  // <--- issue here, creates "undefined" image       

index.jade:

extends layout.jade 

  img(src="#{photo}")  // my problem is here, creating <undefined> tags in html

您可以删除现有的组件内容,然后在 jQuery AJAX 回调中使用 jQuery 重新渲染。有点像..

翡翠:

标签#数据

之后:

脚本。

var socket = io.connect('http://localhost:8898/');
  socket.on('news', function (data) {
      $('#data').text('');    
      $('#data').text(data);
});

可能有点太明显了,但从那个例子来看,但我认为脚本标签内的 JS 块需要缩进。虽然无法测试

script.

    var socket = io.connect('http://localhost:8898/');
        socket.on('news', function (data) {
        console.log("socket.io.on data reaching jade");
        console.log(data); // prints fine, but to console only.
        socket.emit('my other event', { my: data }); 
    });

因为您是从 layout.jade 扩展的,所以 index.jade 是您的子模板。您不需要声明 html 是您的块内容吗?像这样:

extends layout

block content
  #{data}  // my problem is here, creating <undefined> tags in html
      p #{data.stuff}
        img(src="images/bird.jpg")  // works