Skip to content

Instantly share code, notes, and snippets.

@joemaller
Created April 9, 2025 17:17
Show Gist options
  • Save joemaller/915bf411d9203213969f8ceaec46dc1a to your computer and use it in GitHub Desktop.
Save joemaller/915bf411d9203213969f8ceaec46dc1a to your computer and use it in GitHub Desktop.
Use Prettier to format PHP and HTML with a single command in VS Code.

Use Prettier to format HTML & PHP with a single VS Code command

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 Tasks

VS Code user tasks can be configured to run Prettier twice, first for HTML (which ignores PHP code), then again for PHP.

Steps to enable

  1. Open Tasks: Open User Tasks from the command palette
    Add the tasks from this gist's tasks.json file
  2. 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 the editorLangId == php condition prevents it from taking over other files.

Assumptions

The tasks assume Prettier has been installed an configured in the project. Prettier run locally using npx.

Downsides

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.

[
{
"key": "shift+alt+f",
"command": "workbench.action.tasks.runTask",
"when": "editorTextFocus && editorLangId == php",
"args": "Format PHP with Prettier"
}
]
{
"version": "2.0.0",
"tasks": [
{
"label": "Prettier: PHP as HTML",
"type": "shell",
"command": "npx",
"args": ["prettier", "--write", "--parser", "html", "${file}"],
"presentation": {
"reveal": "never",
"showReuseMessage": false
}
},
{
"label": "Prettier: PHP",
"type": "shell",
"command": "npx",
"args": ["prettier", "--write", "${file}"],
"presentation": {
"reveal": "never",
"showReuseMessage": false
}
},
{
"label": "Format PHP with Prettier",
"dependsOn": ["Prettier: PHP as HTML", "Prettier: PHP"],
"dependsOrder": "sequence",
"presentation": {
"reveal": "never",
"showReuseMessage": false
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment