How to format Laravel Blade templates in Visual Studio Code

I tried Laravel Blade Snippets extension but it moves some of the Blade directives into one line.

Then I found this gist where Faizal Dwi Nugraha suggested a hack to support Blade directives for js-beautify used by Beautify extension.

It worked almost perfectly. I forked Faizal’s code and added support for Windows line endings and empty section directives. See instructions and code below for more details.

I have to admit that this process is not very user-friendly. You would have to repeat this every time Beautify extension is updated. Hopefully someone can make it into a separate extension.

Instructions

  1. On Unix, go to ~/.vscode/extensions/HookyQR.beautify-1.3.2/node_modules/js-beautify. On Windows, go to %USERPROFILE%\.vscode\extensions\HookyQR.beautify-1.3.2\node_modules\js-beautify. Use your current version number instead of `1.3.2`.
  2. Edit js/lib/beautify-html.js and add the code from the gist.
  3. Configure VS Code to treat Blade templates as HTML by adding "*.blade.php": "html" to files.associations setting as shown below.

    "files.associations": {
        "*.blade.php": "html",
        // ...
    }
    

    If your Blade templates are configured to be detected as blade format, you may configure Beautify extension to treat blade format as HTML by adding blade to html list of the beautify.language setting.

    "html": [
        "htm",
        "html",
        "blade"
    ]
    
  4. Restart VS Code.
  5. IMPORTANT: Every time when VS Code is updated, check whether the fix is still in place and re-apply if needed.

Code

You May Also Like

Comments

Leave a Reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.