将值从javascript传递给jade

Pass values from javascript to jade

本文关键字:jade javascript      更新时间:2023-09-26

我正在使用node.js,express,jade和 socket.io,我可以让javascript代码在jade端运行,但我无法从脚本生成html。

块我

不得不根据您的输入更新我的问题。以下是文件:

服务器.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");
      });
    });

布局.翡翠:

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       

索引.翡翠:

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