翡翠当地人范围界定

发布于 2024-12-12 04:24:41 字数 577 浏览 0 评论 0原文

在 Jade 模板中使用局部变量时,我遇到范围界定问题。我的代码是...

function(req, res) {
    BlogPostModel.find({}, function(e, data) {
        if (e) throw e;

        posts = data;

        var path = __dirname + "/view/admin/blog.jade",
            template = fs.readFileSync(path, "utf8"),
            options = { filename: path },
            fn = jade.compile(template, options),
            html = fn(posts);

        res.end(html);
});

上面的代码渲染得很好,但是我必须将“data”设置为全局变量。我宁愿将“数据”直接传递到我的函数调用中。但是当我这样做时,我从 Jade 收到“变量未定义”错误。谁能告诉我为什么“数据”超出范围?

谢谢,

FBZ

I have a problem with scoping when using locals in my Jade template. My code is...

function(req, res) {
    BlogPostModel.find({}, function(e, data) {
        if (e) throw e;

        posts = data;

        var path = __dirname + "/view/admin/blog.jade",
            template = fs.readFileSync(path, "utf8"),
            options = { filename: path },
            fn = jade.compile(template, options),
            html = fn(posts);

        res.end(html);
});

The above code renders fine, but I'm having to make 'data' a global variable. I would rather pass 'data' directly into my function call. But when I do that, I get a 'variable is not defined' error from Jade. Can anyone tell my why 'data' is out of scope?

Thanks,

FBZ

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你穿错了嫁妆 2024-12-19 04:24:41

所以这根本不是范围界定问题。我不得不称我的论点为“当地人”。像这样...

BlogPostModel.find({}, function(e, locals) {
    if (e) throw e;
    var path = __dirname + "/view/admin/blog.jade",
        template = fs.readFileSync(path, "utf8"),
        options = { filename: path },
        fn = jade.compile(template, options),
        html = fn(locals);

    res.end(html);
});

Jade 接受任何名称的全局变量,但局部变量必须称为“locals”,这似乎很奇怪。无论如何,排序了。

So it wasn't a scoping problem at all. I had to call my argument 'locals'. Like this...

BlogPostModel.find({}, function(e, locals) {
    if (e) throw e;
    var path = __dirname + "/view/admin/blog.jade",
        template = fs.readFileSync(path, "utf8"),
        options = { filename: path },
        fn = jade.compile(template, options),
        html = fn(locals);

    res.end(html);
});

Seems strange that Jade accepts a global variable of any name, but a local variable must be called 'locals'. Anyway, sorted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文