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

4
  • It does not work THIS way -- you should do OTHER way around: stackoverflow.com/a/12781375/783119 (associate such file with PHP first (e.g. file.js.php) and then "inject" JS) Commented Aug 30, 2013 at 8:48
  • 2
    In fact -- this one is a bit more complete (includes all steps): stackoverflow.com/a/18114575/783119 Commented Aug 30, 2013 at 8: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. Commented Aug 30, 2013 at 9: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... Commented Aug 30, 2013 at 9:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.