How do I get the filename of the executing jade script

余生颓废 提交于 2019-12-08 16:29:21

问题


Is there a global object that is accessible from within a jade template with various parameters?

Is there a global variable with the path of the currently executing jade file?

!!! 5
html
  head
    title Test
  body
    //- I want to be able to know what the current script file is...
    p Hello, I am: #{globals.scriptfilename}

回答1:


If you're using gulp-jade, add gulp-data to the mix and use this code:

var jade = require('gulp-jade');
var data = require('gulp-data');

gulp.src('**/*.jade')
    .pipe(data(function (file) {
        return {
            relativePath: file.history[0].replace(file.base, '')
        };
    }))
    .pipe(jade())

This will give you a relativePath in your jade templates that is something like about/index.jade, relative to the base folder.

I'm not entirely sure of where/how that file.history is generated, but in my case [0] pointed to the original filename (with its absolute path on the disk)




回答2:


My solution:

//gulpfile.js

var $path = require('path'),
    jade  = require('gulp-jade'),
    isProduction = process.env.ENV == 'production';

gulp.task('watch', function() {
    gulp.watch("**/*.jade")
        .on('change', function(event) {
            compileJade(event.path, isProduction);
        });
});

function compileJade(path, isCompress) {
    gulp.src(path)
        .pipe(jade({
            pretty: !isCompress,
            locals: {
                _path_: path,
                _basename_: $path.basename(path)
            }
        }));
}

In Jade file you can use _path_ and _basename_ like this:

<!-- #{_path_}, #{_basename_} -->

One more thing to notice: String interpolation does not work in jade comment. So following code will not interpolated in result html file:

// #{path}



回答3:


There is a global variable. You can use Node's util.inspect(object) to view it's contents.

It automatically replaces circular references with "[Circular]", unlike JSON.stringify().

Using a boilerplate Express app, I found these:

  • global.process.argv == ['node','/Users/mike/Development/test/web.js']
  • global.process.mainModule.filename == '/Users/mike/Development/test/web.js'


来源:https://stackoverflow.com/questions/12262844/how-do-i-get-the-filename-of-the-executing-jade-script

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