【问题标题】:Dynamically load jade templates动态加载翡翠模板
【发布时间】:2013-05-19 09:08:53
【问题描述】:

我正在开发一个小型文档网站,内容存储在文件中。例如,我在 module1/ 目录中有两个文件 chapter1.jadechapter2.jade

我想读取module1/ 目录并在其中动态包含所有chapterX.jade 文件。

我试着做directory = fs.readDirSync('module1/') 然后在我看来:

each item in directory
  include item

但是jade include 不支持动态值(甚至`include #{item})都不起作用。你知道我该如何实现吗?

编辑:我想在each 循环(便于链接的锚点)下生成一些代码,因此解决方案最好在视图中。我显然可以在包含的文件中手动添加锚点,但这并不理想。

谢谢

【问题讨论】:

    标签: view include express pug


    【解决方案1】:

    这是我为使其工作所做的工作的简短版本。它使用jade Public API

    var directory = __dirname+'/views/bla/'
      , files
      , renderedHTML = '';
    
    if( !fs.existsSync(directory) ) {
      // directory doesn't exist, in my case I want a 404
      return res.status(404).send('404 Not found');
    }
    
    // get files in the directory
    files = fs.readdirSync(directory);
    
    files.forEach(function(file) {
      var template = jade.compile(fs.readFileSync(directory+file, 'utf8'));
    
      // some templating
      renderedHTML += '<section><a id="'+file+'" name="'+file+'" class="anchor">&nbsp;</a>'+template()+'</section>';
    });
    
    // render the actual view and pass it the pre rendered views
    res.render('view', { 
      title: 'View',
      files: files,
      html: renderedHTML
    })
    

    而视图只是将 html 变量呈现为未转义:

    div(class="component-doc-wrap")
      !{html}
    

    【讨论】:

    • mmh,不完全是。我想我自己会用 Jade 来进行某种缓存控制
    • 我对 Express/Jade 很陌生,你能给我举个例子吗?谢谢!
    • for-each-ing 文件数组,然后使用jade.renderFile() 将其附加到字符串,并渲染该字符串
    • 感谢您指点方向。 Jade Public API 改变了:stackoverflow.com/a/7294279/999540jade.renderFile() 现在是 jam.compile()
    【解决方案2】:

    正如@user1737909 所说,仅使用翡翠是不可能的。

    最好的方法是构建一个小Express Dynamic (view) Helpers

    在 EXPRESS 3.XX 中删除

    检查这些:Jade - way to add dynamic includes

    【讨论】:

    • 我在询问并看到这篇文章之前做了研究。虽然文档的链接已经失效,而且看起来动态助手是版本 2 的一个功能。我使用的是最新的 Express 3。
    • 是的,动态包含已被删除
    • 那么我们运气不好@kalema。已编辑
    【解决方案3】:

    除了 kalemas 答案,您还可以将您的包含写入到包含在玉中的文件中。

    在此示例中,我将包含内容写入 include_all.jade。该文件包含在一个玉文件中。

    如果它不起作用,请检查路径;-)

    例如 在你的 app.js 中

    var includes = "path/to/include1\n";
    includes += "path/to/include2";
    ...
    incPath = "path/to/include_all.jade";
    
    fs.open(incPath,'w',function(err,fd){
    if(err){
        throw 'error open file: ' + incPath +" "+ err;
    }
    
    var buffer = new Buffer(includes);
     fs.write(fd,buffer,0,buffer.length,null,function(err){
        if (err) 
            throw 'error writing file: ' +err;
        fs.close(fd,function(){
            console.log('file written ' + incPath);
        });
     });
    });
    

    在你的玉文件中

    include path/to/include_all.jade
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-09
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多