【问题标题】:Handlebars Get URL Parameter With If StatementHandlebars 使用 If 语句获取 URL 参数
【发布时间】:2017-04-07 12:14:30
【问题描述】:

我正在使用 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") 这样更改操作 URL,那么它可以工作。

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

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

【问题讨论】:

    标签: express handlebars.js pug


    【解决方案1】:

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

    您可以使用 if 助手有条件地渲染一个块。如果它是 参数返回 false、undefined、null、""、0 或 [],Handlebars 将 不渲染方块。

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

    【讨论】:

    • 我已经像这样修复了您的代码:{{#if user._id}}{{user._id}}{{else}}{{_id}}{{/if}} 并且它现在可以工作了。谢谢。
    • 是的,对不起,我忘记了周围的胡须,我已经更新了答案。很高兴您现在可以运行它。
    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2014-02-01
    相关资源
    最近更新 更多