Search code examples
javascriptgulppugpugjs

Pug JS variable passing


Hello i have problem with passing variable from gulp to pug and then to the filter. Im passing variable like this.

gulp.task('pug-wp', function () {
return gulp.src('src/templates/*.pug')
.pipe(pug({
        pretty: true,
        filters: {
            php: pugPHPFilter
        },
        data: { 
           development: 'php'
        }
    }))
 .pipe(rename({
    extname: ".php"
  }))
  .pipe(gulp.dest(outputPath))
  .pipe(browserSync.stream());

and then i want to use it in

:php(type=development)

and i have error that says

msg: "development" is not constant. All filters are rendered compile-time so                                      filter options must be constants.

Solution

  • Indeed the filter is compiled and so expressions are not available in filter attributes, this is not attributes like for tag elements, this all static but you can use this trick:

    case development
      when 'php'
        :php(type='php')
      when 'foo'
        :php(type='foo')
      when 'bar'
        :php(type='bar')
    

    Or if the developement variable only depends on the environment, just pass the filter dynamically:

    switch (developement) {
      case 'php':
        pugPHPFilter.setSomeDefaultOption({ type: 'php' });
        break;
      case 'foo':
        pugPHPFilter.setSomeDefaultOption({ type: 'foo' });
        break;
    }
    .pipe(pug({
        pretty: true,
        filters: {
            php: pugPHPFilter
        }
    }))
    

    setSomeDefaultOption is an example refer to your pugPHPFilter to find the equivalent function.