1

How can I add automatic language injection for PHP into JavaScript files?

When I add some PHP code into JavaScript the whole syntax highlighting messes up and I got a ton of errors.

I tried to add language injection with ALT+ENTER but I don't get PHP in my list of injections:

screenshot

nicael
  • 18,550
  • 13
  • 57
  • 90
dan-lee
  • 14,365
  • 5
  • 52
  • 77
  • It does not work THIS way -- you should do OTHER way around: http://stackoverflow.com/a/12781375/783119 (associate such file with PHP first (e.g. file.js.php) and then "inject" JS) – LazyOne Aug 30 '13 at 08:48
  • 2
    In fact -- this one is a bit more complete (includes all steps): http://stackoverflow.com/a/18114575/783119 – LazyOne Aug 30 '13 at 08:56
  • @LazyOne The first answer/second answer point 2 solved my problem, thank you! You can put it as answer here if you want. I will accept it then. – dan-lee Aug 30 '13 at 09:23
  • If it is point 2 only, then even first answer is enough (as it includes point 2 only). In any case -- I don't really see the need to copy-paste the same answer across different questions... – LazyOne Aug 30 '13 at 09:33

1 Answers1

1

This won't work. The reason that it cannot be done is that when you load the javascript file in your browser, the PHP code will just appear as plain text, rather than actually be ran to produce the result that you want.

Just to reiterate, you cannot inject PHP code into Javascript files, what you can do however, is have inline javascript, within a file that can handle PHP. For example, if you want the variable contents, you'd have your JS file like follows:

$(function() {
    loadSomething(varNameHere);
});

Then somewhere in the main body of the main, file somewhere that PHP can be ran, you can have this.

?>
<script> var varNameHere = "<?=$somePhp;?>"; </script>
<?php

While not ideal, this is a base example of how it'd work. Hope that helped.

ollieread
  • 6,018
  • 1
  • 20
  • 36