Skip to content

Commit

Permalink
Allow library imports via pug-cli
Browse files Browse the repository at this point in the history
  • Loading branch information
kylekatarnls committed Nov 3, 2017
1 parent 736021b commit 07285df
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 6 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@
"require": {
"php": ">=5.5.0",
"js-phpize/js-phpize-phug": "^1.1",
"nodejs-php-fallback/nodejs-php-fallback": "^1.2",
"nodejs-php-fallback/nodejs-php-fallback": "^1.3.1",
"phug/phug": "^0.1.0",
"phug/js-transformer-filter": "^1.0"
},
Expand Down
10 changes: 6 additions & 4 deletions src/Pug/Engine/PugJsEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,13 @@ public function renderWithJs($input, $filename, $vars = null, $fallback = null)
'pretty' => $this->getDefaultOption('prettyprint'),
'out' => $workDirectory,
];

$optionsFile = $workDirectory . '/options-' . mt_rand(0, 999999999) . '.js';
file_put_contents($optionsFile, 'var locals = ' .
(empty($vars) ? '{}' : json_encode($vars, JSON_UNESCAPED_SLASHES)) . '; ' .
'locals.require || (locals.require = require); ' .
'module.exports = locals;'
file_put_contents($optionsFile, 'module.exports = require(' .
json_encode(realpath(NodejsPhpFallback::getPrefixPath() . '/require.js')) .
').appendRequireMethod(' .
(empty($vars) ? '{}' : json_encode($vars, JSON_UNESCAPED_SLASHES)) .
');'
);
$options['obj'] = $optionsFile;

Expand Down
2 changes: 1 addition & 1 deletion src/Pug/Engine/Renderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function renderString($input, array $vars = [], $filename = null)
};

if ($this->getDefaultOption('pugjs')) {
return $this->renderWithJs($input, null, $vars, $fallback);
return $this->renderWithJs($input, $filename, $vars, $fallback);
}

return call_user_func($fallback);
Expand Down
17 changes: 17 additions & 0 deletions tests/features/pugjs.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use NodejsPhpFallback\NodejsPhpFallback;
use Pug\Pug;

class PugJsTest extends PHPUnit_Framework_TestCase
Expand Down Expand Up @@ -214,4 +215,20 @@ function () {}

self::assertSame('<link rel="shortcut icon" href="/favicon.png" type="image/png"/>', $html);
}

/**
* @group pugjs
*/
public function testLibraryInTemplates()
{
NodejsPhpFallback::installPackages(['moment']);

$pug = new Pug(array(
'pugjs' => true,
));

$html = $pug->render("- moment = require('moment')\np=moment('12-25-1995', 'MM-DD-YYYY').format('DD-MM-YYYY')");

self::assertSame('<p>25-12-1995</p>', $html);
}
}

0 comments on commit 07285df

Please sign in to comment.