Is it possible to write PHP in jade/pug?

前端 未结 5 2220
挽巷
挽巷 2021-02-09 11:37

Is it possible? If so, how? If its not, do I have to abandon pug if I need to write PHP in my documents? After searching around I didnt find anyone that has adressed this.

5条回答
  •  离开以前
    2021-02-09 12:03

    You can embed PHP in Pug templates the same way you would any literal plain text that you want passed through relatively unmolested[*]. There are a number of options covered in the docs, but I think these are most likely the best options for embedding PHP:

    1. After an element, it will just work. For example, p Good morning, name ?>.
    2. On a single line by itself. Since any line beginning with "<" is passed as plain text, any one line PHP statement (e.g., ) will just work.
    3. Multi-line PHP is the one case where it gets a bit complicated. If you're ok with wrapping it in an HTML element, you can use Pug's block text syntax: Put a dot after the element, then include your plain text indented underneath.

      p.
          
      

      If you need it outside an element, the other option is to prefix every line with a pipe:

      |
      

      (Technically, the first line doesn't need to be prefixed due to point 2 above, but if using this method I would prefix it anyway just for consistency.)

    4. To use PHP in attributes, you just need to prevent escaping by prefixing the equals sign with a bang: p(class!=""). (Interestingly, support for unescaped attribute values was added specifically for this use case.)

    Of course by default .pug files are compiled to .html files, so if you're using them to generate PHP, you'll want to change the extension. One easy way to do this is to process them using gulp with the gulp-pug and gulp-rename plugins, which would look something like this:

    var gulp = require('gulp'),
         pug = require('gulp-pug'),
         rename = require('gulp-rename');
    
    gulp.task('default', function () {
        return gulp.src('./*.pug')
            .pipe(pug())
            .pipe(rename({
                extname: '.php'
            }))
            .pipe(gulp.dest('.'));
    });
    

    I haven't worked extensively with Pug, so I don't know if there are any potential gotchas that would come up in real world use cases, but the simple examples above all work as expected.

    [*] Pug still performs variable interpolation on plain text, but it uses the #{variable} format, which should not conflict with anything in PHP's standard syntax.

提交回复
热议问题