Is it possible to write PHP in jade/pug?
Asked Answered
B

6

8

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.

Bawl answered 3/2, 2017 at 11:40 Comment(4)
Is pug a JS library?Twirl
Its a html template.Bawl
Then it's frontend. PHP is backend.Twirl
It's actually not frontend, it is backend. It is a templating engine which has its files compiled to HTML, before being sent to frontend.Calutron
R
12

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.

Reedy answered 6/4, 2017 at 16:53 Comment(1)
I used this approach, it wokrs for me when i was developing simple website. However there are issue i encountered - 1st is syntax not highlighted(writing big chunks of php code is hard to read after), 2nd - woulbe be better to have native support for php inline code in pug, even on small website i met some issue in code so i have to go some strange ways. In big projects i am sure using php in pug the way you described would be very hardMicronutrient
F
3

Since PHP doesn't care whether the "outside" code is HTML or really anything specific, you could simply use PHP as you normally would and have it output Pug-formatted code instead of HTML. For instance:

myPugTemplate.pug.php

html
  head
    title "<?= $this->title ?>"
  body
    <?php
      // Since we're outputing Pug markup, we have to take care of
      //   preserving indentation.
      $indent=str_repeat('  ', 2);
      if ($this->foo) {
        echo $indent . 'bar= myPost';
      } else {
        echo $indent . 'baz= myNav';
      }
    ?>
    footer
      +footerContent

And if your Pug is processed on the server then you'd also include a Pug-processing step, for instance if you use Apache you could use mod_ext_filter configured in such fashion with pug-cli installed:

ExtFilterDefine pug-to-html mode=output intype=text/pug outtype=text/html \
  cmd="pug"

<Location />
  SetOutputFilter pug-to-html
</Location>
Fearsome answered 3/2, 2017 at 16:35 Comment(3)
My understanding of the question is that OP is trying to invoke PHP from within a Pug template, rather than use PHP to generate a Pug template. That is, the webserver is likely a node.js server rather than apache.Nolte
Yea I considered that, but it'd be pretty weird to want to use PHP when what you have is a Node.js server :) In any case it can't hurt to have a clear picture of all the possibilities available.Fearsome
Pug can be used as a preprocessor for writing HTML, much as Sass is when writing CSS, using, for example, gulp-pug. I wouldn't assume Pug automatically means a Node.js server.Reedy
C
1

Have you checked out the pug-php project? I personally have no experience with this particular module, but it seems to do just what you're trying to accomplish: Being able to use PHP in Pug.

Calutron answered 3/2, 2017 at 14:41 Comment(2)
As I understand it, pug-php allows Pug to be used as a template engine from within PHP (much as you might use Twig, for example), not the other way around.Reedy
pug-php also allow you to write PHP code inside pug templates, so yes it's a possibility to do that.Moon
K
1

You can use the scape syntax with quotes:

!{'<?php #php code  ?>'}

For example:

p Hello !{'<?php echo "My name"; ?>'}

Will render:

<p>Hello <?php echo "My name"; ?></p>

You can test it here: https://pug-demo.herokuapp.com/

Klockau answered 23/5, 2017 at 23:18 Comment(0)
G
0

There is a well-known and well-maintained Pug processor written natively in PHP. You can use it to process your Pug files into HTML, just like the original Pug, with the advantage that it allows you to embed and use PHP code in your Pug file with ease. If you're working with PHP inside Pug, check it out:

Phug - the Pug template engine for PHP

Gunslinger answered 8/8, 2019 at 2:32 Comment(1)
author question was a bit different. Phug allows to use PHP as a backend language in templates - for using loops, vars, objects etc. Author and i are looking for a way to incorporate PHP code inside pug templates on 'html-level', meaning to have regular php code outputed after compilation.Micronutrient
P
0
 p Hello !{'<?php echo "My name"; ?>'}

works but

 link(href="../assets/css/style.css?v=!{'<?=$AppsVersion?>'}" rel="stylesheet" type="text/css")

don't work

Patch answered 16/3, 2021 at 23:19 Comment(1)
If you want pug to compile your attribute values, you will have to use != character with the attribute, like so: link(href!="..." )Pokpoke

© 2022 - 2024 — McMap. All rights reserved.