【问题标题】:Serving static files in Express with mustache templating使用 mustache 模板在 Express 中提供静态文件
【发布时间】:2016-06-18 20:59:54
【问题描述】:

我正在尝试从 Express 提供一个包含静态小胡子文件的文件夹,但似乎无法弄清楚如何让它工作。假设我只有一个数据对象,例如

{
  a: 'Hello :)'
  b: 'Goodbye :('
}

还有两个文件,

public/a.html

<div>{{a}}</div>

public/b.html

<div>{{b}}</div>

我怎样才能快速设置到它为任意数量的静态 html 文件提供服务的位置,并用我的一个大对象替换模板化部分?谢谢!

【问题讨论】:

    标签: javascript node.js express mustache middleware


    【解决方案1】:

    静态文件通常仅在发送给用户之前未经过任何处理时才称为static

    您想要实现的是一个典型的模板系统。您可以按照plugin 中的说明进行操作:

    var mustacheExpress = require('mustache-express');
    
    // Register '.html' extension with The Mustache Express
    app.engine('html', mustacheExpress());
    
    app.set('view engine', 'mustache');
    app.set('views', __dirname + '/views'); // you can change '/views' to '/public',
        // but I recommend moving your templates to a directory
        // with no outside access for security reasons
    
    app.get('/', function (req, res) {
        res.render('a');
    });
    

    还可以考虑使用Handlebars,它通常比 Mustache 更方便使用。您可以在this question 中找到差异列表。

    【讨论】:

    • 是的,我之前在谷歌搜索时注意到了该插件,但由于没有文档,我真的很困惑。 res.render('a') 中的 'a' 到底是什么?我希望能够在/views 中拥有任意数量的文件,并让它们都使用相同的数据对象呈现。
    • res.render('a') 中的'a' 是您的模板名称:a.html(无扩展名)。您可以像这样将相同的数据对象传递给每个render() 调用:var data = {a:1,b:2}; res.render('a', data);
    • 那么我如何将 b 也纳入此设置?
    • res.render('b', data); — 如果模板位于带有.html 扩展名的/views 目录中(如上面的代码配置),则会自动加载模板
    • 如果你使用app.engine('html', …),那么你必须使用app.set('view engine', 'html')
    【解决方案2】:

    您可以像 pug 一样在 express 中使用 mustachejs,方法是将 mustache 设置为 view engine 并定义其工作方式,如下所示:

    //required files
    const fs = require("fs")
    const mustache = require("mustache")
    
    // To set functioning of mustachejs view engine
    app.engine('html', function (filePath, options, callback) { 
        fs.readFile(filePath, function (err, content) {
            if(err)
                return callback(err)        
            var rendered = mustache.to_html(content.toString(),options);
            return callback(null, rendered)
        });
      });
    
    // Setting mustachejs as view engine
    app.set('views',path.join(__dirname,'views'));
    app.set('view engine','html');
    
    //rendering example for response
    app.get('/',(req,res)=>{        
        res.render('index',{data:'Sample Data'});
    });

    【讨论】:

      【解决方案3】:

      我稍微修改了 zlumer 的答案,下面的代码对我来说很好。

      const express = require('express');
      const app = express();
      const mustacheExpress = require('mustache-express');
      
      app.engine('html', mustacheExpress());
      
      app.set('view engine', 'html');
      app.set('views', __dirname + '/views');
      
      app.get('/', function(req, res) {
        const data = {
          hello: 'world',
          foo: 'bar'
        };
      
        res.render('test', data);
      });
      
      app.listen(3000, () => {
        console.log('Server running at http://localhost:3000/');
      });
      

      请查看https://github.com/HemingwayLee/sample-mustache-express 并随意克隆和修改它。

      【讨论】:

        【解决方案4】:

        您不应该在公共目录中包含您的 html 文件。公共目录应仅包含图像、javascript 和 css 文件。

        虽然有很多方法可以构建 node/express 应用程序,但您可以使用 Express Generator 找到一种好方法。

        http://expressjs.com/en/starter/generator.html

        如果您使用它,它将为您创建应用程序结构,清楚地说明您应该如何保留静态文件。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多