Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write PHP in jade/pug?

Tags:

html

php

pug

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.

like image 980
student42 Avatar asked Feb 03 '17 11:02

student42


1 Answers

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, <?php echo $user->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., <?php echo $foo; ?>) 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.
        <?php
        if ($multiline) {
            echo 'Foo!';
        }
        ?>
    

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

    |<?php
    |if ($multiline) {
    |   echo 'Foo!';
    |}
    |?>
    

    (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!="<?php echo $foo ?>"). (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.

like image 65
cfc Avatar answered Oct 04 '22 15:10

cfc