2014년 1월 10일 금요일

node.js + express + swig + socket.io

express + swig + socket.io 입니다.
var port=3000;

var swig  = require('swig'),
    express = require('express'),
    app = express(),
    io = require('socket.io').listen(app.listen(port));

    app.engine('html', swig.renderFile);
    app.set('view engine', 'html');
    app.set('views', public_dir);

    // Swig will cache templates for you, but you can disable
    // that and use Express's caching instead, if you like:
    app.set('view cache', false);
    // To disable Swig's cache, do the following:
    swig.setDefaults({ cache: false });
    // NOTE: You should always cache templates in a production environment.
    // Don't leave both of these to `false` in production!
    app.get('/', function (req, res) {
      res.render('index', {  
        pagename: 'awesome people',
        authors: ['Paul', 'Jim', 'Jane']
      });
      
    });

io.sockets.on('connection', function (socket) {
  // socket code
});
이렇게 작성하면 app.get 부분에서 index 에 pagename: 'awesome people', authors: ['Paul', 'Jim', 'Jane'] 이 값을 넘겨줍니다. 그럼 index.html 에선

{{ pagename|title }}

    {% for author in authors %}
  • {{ author }}
  • {% endfor %}
이런 식으로 쓰겠죠..

 참고자료
 swig 예제 : http://paularmstrong.github.io/swig/
 swig + express : http://paularmstrong.github.io/swig/docs/#express
 express + socket.io : http://socket.io/#how-to-use (Using with the Express web framework)

댓글 없음:

댓글 쓰기