Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the filename of the executing jade script

Tags:

pug

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}
like image 833
Billy Moon Avatar asked Sep 04 '12 11:09

Billy Moon


2 Answers

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)

like image 129
fregante Avatar answered Nov 14 '22 23:11

fregante


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}
like image 31
aztack Avatar answered Nov 14 '22 23:11

aztack