Features Releases

Syntax highlighting of PHP inside JavaScript (and other languages)

clip_image001From time to time we have to mix different programming languages in one file. If there is only one or two occurrences of these small, embedded language islands, using Language Injections is the way to go. But what if we have a lot of them?

For example, a JavaScript or CSS file in which we are making use of a PHP variable or function: How do we get mixed syntax highlighting, code completion and inspections? There’s a nice trick to do this: configuring the Template Data Language.

This functionality is available in IntelliJ IDEA, PyCharm, WebStorm, PhpStorm, RubyMine and AppCode for various languages.

We can configure PhpStorm to recognize a file, folder and even an entire project as containing multiple languages. For example, we can use PHP syntax inside JavaScript and echo a specific variable to output. Our IDE will recognize both languages and provides syntax highlighting, code completion, inspections, refactorings and so on.

We can do similar things with CSS and embedded PHP. Here’s a .css.php file for which I’ve specified the Template Data Language as CSS. It features inspections for both the CSS part of the syntax as well as the embedded PHP.

In order to configure syntax highlighting of PHP inside JavaScript (and other languages combinations):

  1. Rename the file from *.js to *.js.php (for example) to have a separate file type for files of this kind.
  2. Associate new file type with PHP in Settings | File Types.
  3. Specify a secondary language for a specific file,  folder or the entire project in Settings | Template Data Languages. For our example, we can select JavaScript.

See the full tutorial: Syntax highlighting of PHP inside JavaScript (and other languages).

Working with mixed syntax in your project? Head over to the tutorials page and learn how to set things up for this to work. Let us hear your thoughts in the issue tracker, through the comments below or in our forums!

Develop with pleasure!
– JetBrains PhpStorm Team

image description