Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly syntax-highlighting javascript in phpstorm

In an existing laravel application I'm working on, .blade.php files contain a body section with my html and php in it. After the body section they contain a custom_js section which is used for inserting javascript code. In the parent template, the custom_js section is embedded like this:

<script>
@include('custom_js')
</script>

I can't get correct syntax highlighting in my .blade.php files for my javascript code. Php and html is highlighted correctly.
If I put the javascript code inside <script> tags the highlighting works fine and that's how the other developers have worked so far but before deployment you will have to remove these tags or else there would be 2 opening and 2 closing <script> tags. I don't feel comfortable with changing the parent template because that would cause enourmous refactoring effort.
I've already tried setting the Template Data Language of this specific file to various languages but that didn't help.

Is there an easy way or do I have to stick with inserting and removing <script> tags manually before deploying?

I'm using PhpStorm 8.0.3.

like image 728
tobifasc Avatar asked Nov 10 '22 07:11

tobifasc


1 Answers

The best solution would be

...is to use comment-style language hinting - something like

// @lang JavaScript
someCode();
// @endlang

Something similar is described with language injecting, but I was not able to make this work in this manner :/ - I will update this if I do, I've started a separate question on the generic matter here:
How to set syntax highlighting to a code section to a specific language programatically/with comments?

Less prettier way

...is to use Language injections directly - right click the code and click Show context actions (or Alt+Enter) => select Inject language or reference => select language of your choosing, although this does highlight the JavaScript, for me it damages the rest of the file's highlighting partially.

Ugly, but generic working solution

...is to trick PHPStorm in a way it thinks you are actually adding a <script> tag, but in fact you will comment it out.

{!! /* JS syntax highlighter !!}<script>{!! */'' !!}
var following = "javascript";
var doer = () => {
   console.log(following);
};

The trick is based of fact that {!! X !!} is actually converted to just <?php echo X; ?> - normally it's a tool for displaying text you don't want to be HTML-escaped.

So the code than becomes

<?php echo /* JS syntax highlighter; ?><script><?php echo */''; ?>

And in the end it just "echos" the empty string.

like image 143
jave.web Avatar answered Nov 14 '22 23:11

jave.web