简体   繁体   English

如何在Meteor中获取文件列表到模板?

[英]How to get a list of files to the template in Meteor?

New to meteor, I'm having a hell of a time with the whole client/server thing. 流星的新手,整个客户端/服务器的事情我都度过了难关。 Super fun. 超级好玩。

I want to read a list of all files that are in a folder, and just print them on the UI, on a template. 我想读取一个文件夹中所有文件的列表,然后将它们打印在UI的模板上。 It has to be possible. 它必须是可能的。 Here's the code. 这是代码。

js file: js文件:

var availableFiles = [];
if (Meteor.isServer) {
    var fs = Npm.require('fs');
    availableFiles = fs.readdirSync(process.env.PWD + '/public/uploads');
    console.log(availableFiles);
}

Router.map(function() {

    this.route('home', {
        path: '/',
        template: 'home',
        data: {files: availableFiles}
    });
});

html file: html文件:

<template name="home">
{{#each data.files}}
    {{this}}
{{/each}}
</template>

I've tried to put the fs calls inside a function on data on the route definition, but I get "Npm is not defined" errors. 我试图将fs调用放在路由定义上的数据上的函数内,但出现“未定义Npm”错误。 I don't know if that's how it should be structured or not, remember, newb here. 我不知道这是应该如何组织的,记住,这里是newb。 Any help would be greatly appreciated. 任何帮助将不胜感激。

I'd probably do this with a reactive array ( http://reactivearray.meteor.com/ ) and a Meteor method. 我可能会使用反应性数组( http://reactivearray.meteor.com/ )和Meteor方法来做到这一点。 Something like: 就像是:

if (Meteor.isServer) {
    var fs = Npm.require('fs');
    Meteor.methods({
        getFiles() {
            return fs.readdirSync(process.env.PWD + '/public/uploads');
        }
    });
}

if( Meteor.isClient ) {
    Template.home.onCreated( function() {
        Template.instance().files = new ReactiveArray();
        Meteor.call('getFiles', function(error, result) {
            if( error ) {
                console.log( error );
            } else {
                Template.instance().files = files.concat( result );
            }
        });
    });
    Template.home.helpers({
        files() {
            return Template.instance().files.array();
        }
    });
}

Router.map(function() {

    this.route('home', {
        path: '/',
        template: 'home',
        data: {files: availableFiles}
    });
});

Syntax might not be perfect, but that should get the point across. 语法可能并不完美,但是应该可以理解这一点。 You'll also need to change your template to {{#each files}} 您还需要将模板更改为{{#each files}}

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

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