Prettier is a fantastic tool, but doesn't natively support PHP. The Prettier PHP Plugin helps, but fully takes over formatting of PHP files and skips HTML in mixed documents.
There is a command-line solution (add --parser html
), but most of the time I'm formatting on-the-fly in VS Code, so dropping out to the command line would be a huge slowdown.
Which brings up another problem: The Prettier VS Code extension hasn't worked with Prettier plugins since August 2023.
But, there's a solution to which works really well, even if it's a little slow.
VS Code user tasks can be configured to run Prettier twice, first for HTML (which ignores PHP code), then again for PHP.
- Open Tasks: Open User Tasks from the command palette
Add the tasks from this gist's tasks.json file - Open Preferences: Open Keyboard Shortcuts (JSON) from the command palette
Add the binding from this gist's keybindings.json file. This uses the same shortcut as the Prettier VS Code extension, but theeditorLangId == php
condition prevents it from taking over other files.
The tasks assume Prettier has been installed an configured in the project. Prettier run locally using npx.
Formatting is not fast. Because the commands write to the file, they need to run sequentially. In most cases you'll see the file flash twice, first with formatted HTML, then again with formatted PHP. It's very slow, but I kind of like it.
The only other minor downside is that the file must be saved in order to work. VS Code will automatically save dirty editors before running tasks on them. So the task will just work correctly.