pug-php / pug

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

Cannot pass variables when including script #221

Closed ttfreeman closed 5 years ago

ttfreeman commented 5 years ago

Hello,

The issue is well explained in this stackoverflow post: https://stackoverflow.com/questions/46600484/pug-pass-variable-to-include-js-file . There seems to be no where to pass variables when including an external script file:

  script
    include dynamicLoad.js 

I need to pass nextPageToken to the script that will be used for fetching data:

if (nextPageToken) {
      fetch(`?pageToken=${encodeURIComponent(nextPageToken)}`)
        .then(r => r.json())
        .then(data => console.log(data))
        .catch(e => console.log("Booo"));

Thanks!

kylekatarnls commented 5 years ago

Hello,

You can use interpolation

script
  | var nextPageToken = '#{nextPageToken}';
  include dynamicLoad.js 

Supposing you have the token as string in your template variables, it will pass it to JS.

Please note than include in script will dump the JS code, it's not optimized, to load it in a parallel request and benefit the cache browser, use:

script
  | var nextPageToken = '#{nextPageToken}';
script(src="dynamicLoad.js")
ttfreeman commented 5 years ago

@kylekatarnls Thanks. I had tried those methods too before but they result in script file being completely ignored. For instance, if I have a button that is supposed to console.log the nextPageToken by click, after using your suggested codes, the button does nothing and no error being thrown out either. I tried adding a dot after script and various combination of indents and still no functionality except for using "include" without a var defined but that throws an error for nextPageToken not defined.

kylekatarnls commented 5 years ago

My test:

index.php

<?php

include __DIR__ . '/vendor/autoload.php';

$pug = new Pug();

echo $pug->render("script
  | var foo = '#{foo}';
  include my-script.js
", [
    'foo' => 'bar',
]);

my-script.js

console.log(foo);

HTML output:

<script>var foo = 'bar';
console.log(foo);
</script>

So it logs "bar" as expected.

You're issue is more likely a JS issue in your script (closure, scope of variables), or a problem with your data, else provide a minimum code example to reproduce your bug (please follow the issue template)