【问题标题】:Can partials access locals in sails? why not?partials 可以在风帆中访问当地人吗?为什么不?
【发布时间】:2015-04-03 16:32:51
【问题描述】:

我的主页有一个index.ejs,它为我的注册页面呈现<%- partial ('../user/new.ejs') %>。在添加 flash 错误消息的过程中,我注意到部分无法访问 locals [flash undefined error]。同时,如果我将部分加载为视图(通过直接访问root/user/new,则闪存消息将正确执行。

有人能解释一下为什么会这样吗?有什么解决办法吗?

潜在原因:index.ejs 是通过res.redirect 加载的,同时专用注册视图是通过res.view 加载的?

控制器:

create: function (req, res, next) {

    User.create({
        email: req.param('email'),
        encryptedPassword: req.param('password')
    }, function userCreated(err, user) {
        if (err) { 
            console.log(err); 

            req.session.flash = {
                err: err.ValidationError
            }

            return res.redirect('/');
        }
        res.redirect('/user/show/'+ user.id);
        //res.json(user);
    });
},

index.ejs 现在只是 <%- partial ('../user/_signup.ejs') %>

_signup.ejs

<div class="col-sm-12 col-md-12 col-lg-12" style="max-width:400px;">
<h1>Sign up</h1>
<form action="/user/create" method="post" role="form" class="form-signin">


<% if(flash && flash.err) { %>
    <ul class="alert alert-success">
    <% Object.keys(flash.err).forEach(function(err) { %>
        <li> <%- JSON.stringify(flash.err[err]) %></li>
    <% }) %>
    </ul>
<% } %>

    <div class="form-group control-group"> 
        <label for="email"></label>
        <input name="email" class="form-control" placeholder="Email" type="text"/>
    </div>

    <div class="form-group control-group"> 
        <label for="password"></label>
        <input name="password" class="form-control" placeholder="Password" id="password" type="password" title="Password"/>
    </div>

    <div class="form-group control-group"> 
        <label for="passwordConfirmation"></label>
        <input name="passwordConfirmation" class="form-control" placeholder="Confirm Password" type="password" title="Password"/>
    </div>

    <input type="submit" value="Signup" class="btn btn-success"/>
    <input type="hidden" name="_csrf" value="<%= _csrf %>"/>
</form> 

【问题讨论】:

    标签: node.js model-view-controller sails.js


    【解决方案1】:

    partial 绝对应该可以访问您在渲染视图时发送的任何本地人,所以看起来这里可能会发生其他事情。无论如何,您可以通过将变量作为第二个参数发送来手动将其传递给部分:

    <%- partial ('../user/new.ejs', {flash: flash}) %>
    

    【讨论】:

    • 这不起作用,我仍然从index.ejs 获得flash undefined。我的下一个猜测是本地人没有完全从userController 传递过来。难道是因为我在分配req.session.flash而不是使用res.view之后将redirect设置为root?
    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多