简体   繁体   English

用户空格键和模板助手在Meteor中随机加载为页面背景

[英]User Spacebars and Template Helpers to load random as page background in Meteor

I am trying to load a random background image anytime someone visits a page, and I found an answer on SO that says I should be able to, but I can't seem to get it working. 每当有人访问页面时,我都试图加载随机的背景图像,我在SO上找到了一个答案,说我应该可以,但似乎无法正常工作。

Answer I am referring to: Mixing handlebars.js and CSS - Random background image? 我指的是: 混合handlebars.js和CSS-随机背景图像?

My code looks as follows: 我的代码如下所示:

header.html: header.html:

 <div class="backgroundImage"> stuff </div>

header.js: header.js:

loadbg: function() {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "/backgrounds", false); // false for synchronous request
    xmlHttp.send(null);
    var returnedData = JSON.parse(xmlHttp.responseText);
    //console.log(returnedData[randomNumber(2, returnedData.length)]);
    var randomImageName = returnedData[randomNumber(2, returnedData.length)];
    var path = "../images/background/"+randomImageName;
    console.log(path);
    return randomImageName;   
}

header.less: header.less:

background-image: url({{loadbg}});

My console.log() doesn't seem to fire so I am not sure what is going on.... 我的console.log()似乎没有启动,所以我不确定发生了什么...。

This approach seems a little bit hacky, but the general idea is that you store your images in a collection managed by Meteor-CollectionFS : 这种方法似乎有点棘手,但通常的想法是将图像存储在由Meteor-CollectionFS管理的集合中

  1. Run meteor add cfs:standard-packages cfs:filesystem . 运行meteor add cfs:standard-packages cfs:filesystem
  2. Run mkdir -p public/bg_images in your project root. 在项目根目录中运行mkdir -p public/bg_images
  3. Copy your images to /public/bg_images . 将图像复制到/public/bg_images
  4. Define the Images collection, for example in your common.js : 定义Images集合,例如在common.js

Images = new FS.Collection("images", {
    stores: [new FS.Store.FileSystem("images", {path: "~/public/bg_images"})]
});

  1. Unfortunately, the file management solution provided by CollectionFS does not recognise manual changes made to the /public/bg_images directory. 不幸的是, CollectionFS提供的文件管理解决方案无法识别对/public/bg_images目录进行的手动更改。 As a result, we need to implement a mirroring mechanism to map the images stored on your file system with the corresponding collection: 因此,我们需要实现一种镜像机制,以将存储在文件系统中的图像与相应的集合进行映射:

if (Meteor.isServer) {
    Meteor.startup(function () {
        exec = Npm.require('child_process').exec;
        var fs = Npm.require('fs');
        var filesToMirror = [];
        child = exec('ls -m ' + process.env.PWD + '/public/bg_images/ | tr -d \' \n\' ', Meteor.bindEnvironment(function (error, stdout, stderr) {
            if (error !== null) {
                console.log('exec error: ' + error);
            }
            filesToMirror = stdout.split(',');
            console.log("Files to mirror:");
            console.log(filesToMirror);
            for (var i = 0; i < filesToMirror.length; i++) {
                fs.readFile(process.env.PWD + '/public/bg_images/' + filesToMirror[i],
                    Meteor.bindEnvironment(function (err, data) {
                        if (err) throw err;
                        var newFile = new FS.File();
                        newFile.attachData(data, {type: 'image/jpg'}, function (error) {
                                if (error) throw error;
                                newFile.name(filesToMirror[i]);
                            },
                            function (e) {
                                throw e;
                            });
                        Images.insert(newFile);
                    })
                )
            }
        }));
    });
}

  1. Implement a template helper which returns the preferred image: 实现一个模板助手,该助手返回首选图像:

Template.background.helpers({
    image: function () {
        // Return random document of 'Images' collection, e.g.:
        return Images.findOne({}, {skip: Math.floor(Math.random() * Images.find().count()), limit: 1});
    }
});
  1. Include your template helper: 包括您的模板助手:

<template name="background">
    {{#with image}}
        <img src='{{this.url}}'>
    {{/with}}
</template>

Please note: The proposed code in step 5 will add all images in /public/bg_images to your collection every time the server (re)starts. 请注意:每次启动(重新)服务器时,步骤5中建议的代码都会将/public/bg_images所有图像添加到您的集合中。 As a consequence, you may want to clear your Images collection prior to that. 因此,您可能需要在此之前清除Images集合。

I don't believe that Meteor will perform a substitution into your header.less file. 我不相信Meteor会在您的header.less文件中执行替换操作。 That file is being preprocessed into the master css file long before your header loads. 在加载标题之前,该文件已被预处理为CSS主文件。

As shown in the answer to the question you link to, you can put <style> settings in your html template file directly and the substitution can happen there. 如您所链接问题的答案所示,您可以将<style>设置直接放在html模板文件中,替换就可以在其中进行。 Alternatively you can set the background image in js using jQuery: 或者,您可以使用jQuery在js中设置背景图片:

$('.backgroundImage').css('background-image','url(' + imageUrl + ')');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM