pug-php / pug

Pug template engine for PHP
https://www.phug-lang.com
MIT License
391 stars 42 forks source link

How to use closure if render engine is pugjs #142

Closed thiennq closed 7 years ago

thiennq commented 7 years ago

Hi,

I'm using pugjs engine and I can't using closure in .pug file. Did I do something wrong?

Here's my code:

View.php

class View {
  public function __construct($obj) {
    $viewConfig = array(
      'pugjs' => true,
      'expressionLanguage' => 'js'
    );
    $pug = new Pug($viewConfig);
    $this->pug = $pug;
  }

  public function render($response, $file, $data = array()) {
    try {
      $double = function ($str) { return $str . $str; };
      $closures = [
         'double' => $double
      ]

      $filepath = $this->path . $file;
      $html = $this->pug->render($filepath, $data, $closures);
      $body = $response->getBody();
      $body->write($html);
    } catch (Exception $e) {
      ....
    }
 }
 ....

index.pug:

h1=double("abc")

Thank you!

kylekatarnls commented 7 years ago

->render has only 1 array argument. In your code only $data is available in the templates, $closures is ignored. Use this:

$html = $this->pug->render($filepath, array_merge($data, $closures));
thiennq commented 7 years ago

@kylekatarnls Thank you, I'll try it.

kylekatarnls commented 7 years ago

Oh, and I'm sorry but functions cannot be passed throught pugjs engine. The pugjs option will convert all data as a JSON string and pass it to pug-cli. JSON can contain only strings, numbers, booleans, null, array, standard objects.

thiennq commented 7 years ago

@kylekatarnls: Thank for the great explanation 👍

I tried to change config:

    $viewConfig = array(
      'expressionLanguage' => 'js'
    );

use php engine but expressionLanguage is js and it works perfectly for me. The syntax likes original pugjs but support php function (global function).

thiennq commented 7 years ago

Here the full solution:

view.php

require_once('pug-helper.php');

class View {
  public function __construct($obj) {
    $viewConfig = array(
      'expressionLanguage' => 'js'
    );
    $pug = new Pug($viewConfig);
    $this->pug = $pug;
  }

  public function render($response, $file, $data = array()) {
    try {
      $filepath = $this->path . $file;
      $html = $this->pug->render($filepath, $data, $closures);
      $body = $response->getBody();
      $body->write($html);
    } catch (Exception $e) {
      ....
    }
 }

pug-helper.php

function money($money) {
  return '$' . number_format($money);
};

index.pug

p=money(12345)

The result:

<p>$12,345</p>