Unable to include relative path file using Jade Template

橙三吉。 提交于 2021-01-27 04:11:52

问题


I'm receiving the following error when I'm attempting to include a file in the same folder:

the "filename" option is required to use "include" with "relative" paths 

There are two files:

index.jade

list_of_items.jade

.content-container
  .row
    .col-lg-10.col-lg-offset-1.col-xs-12
      .row
        .col-xs-3
          include list_of_items
        .col-xs-9
          include content

I tried to use base path, but then received the following error:

the "basedir" option is required to use "include" with "absolute" paths

The code for the base path is as follows:

.content-container
  .row
    .col-lg-10.col-lg-offset-1.col-xs-12
      .row
        .col-xs-3
          include /User/project/list_of_items
        .col-xs-9
          include content

I'm completely at a loss. Is there another setting somewhere that I am missing? It feels like this should be something super simple. What am I missing?


回答1:


You are using jade.compile(), right? As the error message states, you are not passing the filename option. Since you are only giving a string to compile to Jade, it does not know where to look for the included files.

An example where the script and the jade files are in the same folder. The index.jade file includes another file using include foo:

var jade = require('jade'),
    fs   = require('fs'),
    path = require('path');

var fn = jade.compile(fs.readFileSync('index.jade', 'utf-8'), {
  filename: path.join(__dirname, 'index.jade'),
  pretty:   true
});

console.log(fn());

Or with "absolute paths" that in Jade are absolute in reference to the given basedir you would do the following. The index.jade file now includes the same file but using absolute path, ie. include /foo:

var jade = require('jade'),
    fs   = require('fs');

var fn = jade.compile(fs.readFileSync('index.jade', 'utf-8'), {
  basedir: __dirname,
  pretty:  true
});

console.log(fn());

For all options see the API docs.




回答2:


You can render dynamic template using function in locales. This method also support filters.

Jade file

+render('contents/index.md', {filter:'marked'});

Gulp Pipe

.pipe(jade({
  locals: {
    render: function (filePath, options) {
      return jade.render(`include${options.filter ? (':' + options.filter) : ''} ${filePath}`, {
        filename: pathToJadeFileDir + '/something-not_important'
      });
    }
  }
}))


来源:https://stackoverflow.com/questions/28038630/unable-to-include-relative-path-file-using-jade-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!