使用Express和EJS动态显示图像 [英] Display dynamically an image using express and EJS

查看:58
本文介绍了使用Express和EJS动态显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含不同图像URL的集合.我检索了想要的URL,并希望将其传递给jade模板,例如:

I have a collection containing different URLs of images. I retrieve the URL I want and want to pass it to the jade template like:

app.get('/',function(req,res){
    mongoDB.getUsedHomePageOne(function(err, result){
        if(!err){
            console.log("getUsedHomePageOne : ");
            console.log(result);
            app.locals['homePageImg'] = result.url;
        }
    });

    app.render('userPageEjs.html',function(err,renderedData){
        console.log(renderedData);
        res.send(renderedData);
    });
});

和getUsedHomePageOne看起来像:

and the getUsedHomePageOne looks like:

DBMongo.prototype.getUsedHomePageOne  = function(callback){
    this.homePageColl.findOne({used:1}, callback);
};

并在玉模板中:

<img src="<%= homePageImg %>"/>

因此,除非我加载两次页面,否则这将不起作用,我认为是因为它被缓存并且计算速度足够快.

So this won't work except if I load twice the page, I assume because it gets cached and is computed quickly enough or something.

正确的做法是什么?

PS:第二次加载页面时,所有内容都会正确加载.

PS: the 2nd time I load the page, everything will load correctly.

PS2:我不想延迟图像的渲染,我想在图像准备好后立即加载,但是无论如何都要渲染HTML页面.

PS2: I don't want to delay the rendering for the image, I would like to load the image once it is ready, but render the HTML page before anyway.

推荐答案

根据我在您的代码中收集到的信息:

From what I've gathered in your code:

app.get('/',function(req,res){
    mongoDB.getUsedHomePageOne(function(err, result){
        if(!err){
            console.log("getUsedHomePageOne : ");
            console.log(result);
            app.locals['homePageImg'] = result.url;
            app.render('userPageEjs.html',function(err,renderedData){
               console.log(renderedData);
               res.send(renderedData);
            });
        }
    });
});

基本上,您对数据库具有异步功能,并且在等待数据库功能完成之前可以快速呈现模板.使用异步函数(其结果应在行下使用)时的正常模式,您必须在异步函数内调用下一个函数.但是,这可能会导致回调地狱(类似于我上面编写修复程序的方式),因此通常首选Promises或async.js之类的替代方法.

Basically, you have an async function to the DB and you quickly render the template before waiting for the DB function to complete. The normal pattern when using async functions whose results should be used down the line, you have to call the next function inside the async function. However, this might lead to callback hell (similar to how I've written the fix above), so an alternative like Promises or async.js is usually preferred.

这篇关于使用Express和EJS动态显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆