express + hogan如何处理会话?

时间:2015-07-23 10:49:13

标签: javascript node.js session express hogan.js

我使用expressjshoganjs下面的package.json是我的Index.hjs和设置。我有疑问是否必须检测会话并在hoganjs内只给出一部分不同的布局 我该怎么办?

我在routes/Index.js找不到任何关于会话的文档,它似乎只处理模板逻辑 - 少? 那么这是否意味着我必须在{ "name": "app", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.13.2", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "express": "~4.13.1", "hjs": "~0.0.6", "less-middleware": "1.0.x", "morgan": "~1.6.1", "pg": "^4.4.0", "serve-favicon": "~2.3.0" } } 中检测并呈现不同的文件?怎么做这个例子?

如果我必须让两个文件有重复的部分,那么我试图找到像extend,include方法这样的方法,所以我找到了load other template file inside template,但它似乎不方便,所以我常常想知道人们如何这样做?

的package.json

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// end: view engine setup

...

// route handler to each routes
require('./RouteHandler.js')(app, express);
// end: route handler to each routes
...

app.js

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');


var setupRoutes = function(app, express) {
  // uncomment after placing your favicon in /assets
  //app.use(favicon(path.join(__dirname, 'assets', 'favicon.ico')));
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(require('less-middleware')(path.join(__dirname, 'assets')));
  app.use(express.static(path.join(__dirname, 'assets')));


  var routesIndex = require('./routes/Index');
  var routesAccount = require('./routes/Account');

  app.use('/', routesIndex);
  app.use('/account', routesAccount);

  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  });
}


module.exports = setupRoutes;

RouteHandler.js

var express = require('express');
var router = express.Router();


router.get('/', function(req, res, next) {
  ...

  res.render('Index/Index', { title: 'Express' });
});


module.exports = router;

路由/ Index.js

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <!-- session exist -->
    <!-- logged in layout -->
    <!-- end: session exist -->

    <!-- session exist -->
    <!-- logged out layout -->
    <!-- end: session exist -->

    ... both 
  </body>
</html>

Index.hjs

<?php
$imageQueryResult = $this->getUserImages('download', array('i.image_name'));

if(!empty($imageQueryResult)) {
  $imageUrl = $this->getFromAmazon('download', $imageQueryResult);

  $imageNumber = 1;
  $zipName = 'tt-'.date("Y-m-d").'.zip';

       //create new zip object
  $zip = new ZipArchive();

       //create a temp file &amp; open it
  $tmp_file = tempnam('.','');
  $zip->open($tmp_file, ZipArchive::CREATE);

       //loop through each file
  foreach($imageUrl as $image){
          //Get extension
    $ext = pathinfo(parse_url($image, PHP_URL_PATH), PATHINFO_EXTENSION);

           //download file
    $download_file = file_get_contents($image);

           //add it to the zip
    $zip->addFromString(basename($imageNumber.'-tt.'.$ext),$download_file);


    $imageNumber++;
  }

       //close zip
  $zip->close();

      //send the file to the browser as a download
  header('Content-disposition: attachment; filename='.$zipName);
  header('Content-Length: ' . filesize($tmp_file));
  header('Content-type: application/zip');
  readfile($tmp_file);
  ignore_user_abort(true);
  unlink($tmp_file);
  ?>

2 个答案:

答案 0 :(得分:1)

Hogan无法处理会话。 Express就是这么做的。您需要有一个会话存储,可以将您想要的东西存储在req对象中。 根据您存储的值,您可以将值传递给模板并加载任何值。

会话商店 - https://github.com/expressjs/session

Index.js

//设定值

req.session.user.loggedIn = true;

//传递给模板

res.render('Index/Index', { title: 'Express', 'loggedIn': req.session.user.loggedIn });

// in template            
if (loggedIn) {
 <p>Logged in</p>
} else {
 <p>Not logged in</p>
}

修改 - 添加了详细信息

答案 1 :(得分:1)

  

我在hoganjs中找不到关于会话的任何文档,它似乎只处理模板?

Hogan是模板引擎。 所有它都是流程模板。你是对的。 (见:what is a template engine?

  

这是否意味着我必须在routes / Index.js中检测并呈现不同的文件?

不。

您应该做的是,渲染一个模板,但在该模板中,有条件地显示菜单项

{{#user}}
  <li><a href="/dashboard">Dashboard</a></li>
  <li><a href="/logout">Logout</a></li>
{{/user}}

{{^user}}
  <li><a href="/login">Login</a></li>
{{/user}}

在Hogan中,您可以使用上述语法表达与if语句等效的内容。 (见:Hogan If Statements。)

如果有的话,您需要某种方法将user实例传递给模板。您可以在路由处理程序中执行此操作:

app.get('/', function(req, res) {
   if (req.isAuthenticated()) {
     res.render('home', { user: req.user });
   } else { 
     res.render('home');
   }
});

或者在可能的情况下,您希望在每个页面上显示菜单 - 可能在布局中 - 您可以创建middleware

app.use(function(req, res, next) {
  if (req.isAuthenticated()) {
    res.locals.user = req.user;
  }
  next();
});

在上面的示例中,我使用的是Passport中间件。您将需要实现自己的身份和身份验证系统,但这不在本问题的范围内。