phug-php / phug

Phug - The Pug Template Engine for PHP
https://phug.selfbuild.fr
MIT License
63 stars 3 forks source link

Accessing globals like $_SERVER #35

Closed a666 closed 6 years ago

a666 commented 6 years ago

Hello,

I am trying to understand the following behavior: with $_SERVER['URL'] = 'https://example.com'

- $url = $_SERVER['URL']
a(href=$url) test1
a(href=$_SERVER['URL']) test2

I expected to get:

<a href="https://example.com">test1</a>
<a href="https://example.com">test2</a>

But I actually get:

<a>test1</a>
<a href="https://example.com">test2</a>

Is there a way to assign $_SERVER['URL'] to a variable in the same pug file?

Thanks!

kylekatarnls commented 6 years ago

First, if you use the option 'expressionLanguage' => 'php', you code will work just fine. But you have to choice a expression style (they cannot be mixed in the same template).

$pug = new Pug([
  'expressionLanguage' => 'php',
]);

If you want to keep JS-style, you simply should pass variables you need as locals: template.pug:

a(href=host) test1
a(href=server['HTTP_HOST']) test2
$pug = new Pug([
  'expressionLanguage' => 'js', // default value
]);
$pug->renderFile('template.pug', [
  'host' => $_SERVER['HTTP_HOST'], // use only the specific value you need (recommended)
  'server' => $_SERVER, // or give access to the whole superglobal (not recommended)
]);
a666 commented 6 years ago

Wonderful. Solved, thank you.