Handlebars使用If语句获取URL参数

时间:2016-11-23 13:01:12

标签: express handlebars.js pug

我正在用expressjs构建一个简单的CRUD操作。我的应用程序运行良好的默认模板引擎Jade,但我想尝试Handlebars模板引擎express-handlebars。在把手中,如何在URL中使用if语句? 我在我的Jade模板中有这个代码:

[...]

form(action="/users/edit/#{ (_id == undefined) ? user._id : _id }", method="POST").form-horizontal

[...]

然后我将这些代码更改为把手:

[...]    

<form class="form-horizontal" action="/users/edit/{{ _id undefined ? user._id : _id }}" method="post">

[...]

我收到了这个错误:

Error: Missing helper: "_id"
    at Object.<anonymous> (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js:19:13)
    at Object.eval [as main] (eval at createFunctionContext (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:9:79)
    at main (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:173:32)
    at ret (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:176:12)
    at ret (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21)
    at ExpressHandlebars._renderTemplate (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/express-handlebars/lib/express-handlebars.js:247:12)
    at ExpressHandlebars.<anonymous> (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/express-handlebars/lib/express-handlebars.js:173:21)

我再次尝试使用此代码:

<form class="form-horizontal" action="/users/edit/{{#if _id undefined}} user._id {{else}} _id {{/if}}" method="post">

仍有错误:

 TypeError: Cannot read property 'hash' of undefined
    at Object.<anonymous> (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/helpers/if.js:16:17)
    at Object.eval [as main] (eval at createFunctionContext (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:9:32)
    at main (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:173:32)
    at ret (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:176:12)
    at ret (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21)
    at ExpressHandlebars._renderTemplate (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/express-handlebars/lib/express-handlebars.js:247:12)
    at ExpressHandlebars.<anonymous> (/home/bill/Websites/public_html/nodejs-apps/codepolitan-demohbs/node_modules/express-handlebars/lib/express-handlebars.js:173:21)

这是我的用户路线(编辑操作):

router.put('/edit/(:id)', Auth.login, Auth.is_admin, function(req, res, next) {
  session_store = req.session;

  req.assert('username', 'Name is required').isAlpha().withMessage('Required letter or number').notEmpty();
  req.assert('email', 'Invalid Email').notEmpty().withMessage('Empty Email').isEmail();
  req.assert('firstname', 'Required letter or number').isAlpha();
  req.assert('lastname', 'Required letter or number').isAlpha();

  var errors = req.validationErrors();
  console.log(errors);

  if (!errors) {
    v_username  = req.sanitize('username').escape().trim();
    v_email     = req.sanitize('email').escape().trim();
    v_firstname = req.sanitize('firstname').escape().trim();
    v_lastname  = req.sanitize('lastname').escape().trim();
    v_admin     = req.sanitize('admin').escape().trim();

    User.findById(req.params.id, function(err, user) {
      user.username   = req.param('username');
      user.email      = req.param('email');
      user.firstname  = req.param('firstname');
      user.lastname   = req.param('lastname');
      user.admin      = req.param('admin');

      user.save(function(err, user) {
        if (err) {
          req.flash('msg_error', 'Error!!!');
        } else {
          req.flash('msg_info', 'Success!!!');
        }

        res.redirect('/users/edit/'+req.params.id);
      });
    });
  } else {
    // displaying an error
    errors_detail = "<p>Please check your data.</p></ul>";

    for(i in errors) {
      error = errors[i];
      errors_detail += '<li>'+error.msg+'</li>'
    }

    errors_detail += '</ul>';

    req.flash('msg_error', errors_detail);
    res.render('users/edit', {
      _id           : req.params.id,
      session_store : session_store,
      username      : req.param('username'),
      email         : req.param('email'),
      firstname     : req.param('firstname'),
      lastname      : req.param('lastname')
    });
  }
});

顺便说一句,如果我像这样action="/users/edit/#{{ user._id }}", method="POST")更改动作网址,那么它就可以了。

但我只是想知道是否可以做上述事情?

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

从文档(http://handlebarsjs.com/builtin_helpers.html):

  

您可以使用if帮助器有条件地渲染块。如果它是   参数返回false,undefined,null,“”,0或[],Handlebars会   不渲染块。

{{#if user._id}}{{user._id}}{{else}}{{_id}}{{/if}}