-1

so i am declaring a variable inside of a .php file

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/script/jscript_pages.js">
        var templatePath = "<?php bloginfo('template_directory'); ?>";
    </script>

But i want to use the variable templatePath inside of jscript_pages.js but when i do it like this my console says: Uncaught ReferenceError...

I hope someone can help :)

Thanks

Tim Daubenschütz
  • 2,053
  • 6
  • 23
  • 39

4 Answers4

4

The content of a script element is alternative content to use if the browser doesn't support src, it isn't a script to run before running the external script.

Use two script elements.

<script>
    var templatePath = "<?php bloginfo('template_directory'); ?>";
</script>
<script src="<?php bloginfo('template_directory'); ?>/script/jscript_pages.js"></script>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Set the variable before you reference it in script.

<script>
    var templatePath = "<?php bloginfo('template_directory'); ?>";
</script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/script/jscript_pages.js">
</script>
njr101
  • 9,499
  • 7
  • 39
  • 56
1

As @Quentin said, it's either/or in a single tag.

In concept, you can do what you're looking for by having two script tags

<script type='text/javascript'>      
            var templatePath = "<?php bloginfo('template_directory'); ?>";
        </script>
    <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/script/jscript_pages.js"></script>

But, in practice what's usually better (for testing, portability, etc) is for your script file to just define functions and then have your on-page scripts (if you have them) call those functions and apply the variables.

Paul
  • 35,689
  • 11
  • 93
  • 122
0

In this setup, your function bloginfo('template_directory'); should return a $GLOBALS variable.

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129