将值从javascript传递给jade

时间:2016-02-22 17:23:09

标签: javascript node.js express socket.io pug

我正在使用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

3 个答案:

答案 0 :(得分:0)

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

玉:

标签#数据

后:

脚本。

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

答案 1 :(得分:0)

可能有点太明显但是从那个例子开始,但我认为脚本标签内的JS块需要缩进。虽然

,但是Haven还是能够测试一下
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 }); 
    });

答案 2 :(得分:0)

由于您是从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