为 keystone.js 中带有车把的 CloudinaryImage 对象应用下划线方法

Applying underscore methods for CloudinaryImage objects in keystone.js with handlebars

我想在我的 keystone.js 应用中使用 Cloudinary 调整上传图像的大小和质量。

关于如何使用 cloudinary 的下划线方法的所有示例(在 github 上)都写在 pug/jade 中。参见示例(来自 https://github.com/keystonejs/keystone-demo/blob/master/templates/views/gallery.jade):

img(src=image.fill(300,300), alt=gallery.name + ' image ' + (i+1)).img-thumbnail

如何将其转化为车把?我对 jade/pug 有点陌生,我一辈子都弄不清楚这里到底发生了什么。

请注意,这是类似的示例,而不是您引用的实际代码。

假设

Image = function(url) {
    this.url = url;
    this.fill = (sizeX, SizeY) => {
        return `${this.url}/${sizeX}x${sizeY}.png`;
    }
}


galleries = [
    {
        name: 'Gallery1',
        images: [
            new Image('img/gallery/1/image/1'),
            new Image('img/gallery/1/image/2')
        ]

    },
    {
        name: 'Gallery2',
        images: [
            new Image('img/gallery/2/image/1'),
            new Image('img/gallery/2/image/2'),
            new Image('img/gallery/2/image/3')
        ]
    }

];

然后关注

for gallery in galleries
    for image in gallery
        img(src=image.fill(300,300), alt=gallery.name + ' image ' + (i+1)).img-thumbnail

等同于

<img class="img-thumbnail" src="img/gallery/1/image/1/300x300.png" alt="Gallery1 image 1" />
<img class="img-thumbnail" src="img/gallery/1/image/1/300x300.png" alt="Gallery1 image 2" />

<img class="img-thumbnail" src="img/gallery/2/image/1/300x300.png" alt="Gallery2 image 1" />
<img class="img-thumbnail" src="img/gallery/2/image/2/300x300.png" alt="Gallery2 image 2" />
<img class="img-thumbnail" src="img/gallery/2/image/3/300x300.png" alt="Gallery2 image 3" />

几个月大了,但我自己就把头撞在墙上了。我终于 "shotgunned" 它直到我找到了有效的方法。这对我有用:

  1. 将代码放在路由文件夹中的 javascript 文件中,基本上是控制器。
  2. 在该文件中,将代码放入 exec 方法中。下面是我在 about.js 文件中为变量 locals.myPicture.

    所做的片段
    var keystone = require('keystone');
    
    exports = module.exports = function (req, res) {
    
    var view = new keystone.View(req, res);
    var locals = res.locals;
    
    // Set locals
    locals.section = 'about';
    locals.welcome = "";
    locals.background;
    locals.myPicture;
    
    view.on('init',function (next) {
        var q = keystone.list('About').model.find().where('defaultAbout').eq(true);
    
        q.exec(function (err, result) {
            locals.welcome = result[0].welcome;
            locals.background = result[0].backGround.url;
            locals.myPicture = result[0]._.heroImage.fit(400,400);
    
            next(err);
        });
    })
    
    
    
    // Render the view
    view.render('about');
    };
    

对于某些上下文,我有一个关于页面,其中可以有多个配置文件。字段 defaultAbout 是一个布尔字段,它将关于配置文件设置为要在关于页面上显示的默认配置文件。此外,我正在使用 Handlebars,但我不必在视图中执行任何有关下划线方法的操作。

对于多张图片,我想你可以用 "for" 循环做同样的事情,但我还没有这样做......还没有。希望这对某人有所帮助,尽管我不能保证我的做法是最佳做法。