How to Format Laravel Blade Code in Visual Studio Code?
Asked Answered
K

14

71

I have installed some Visual Studio Code extensions to handle Laravel Blade Code like

But they are not helping me to format Laravel Blade Code [blade.php files]. I mean they are not auto indenting the code as I expected. But I have seen blade code online which are well indented in visual studio Code IDE.

Example :

enter image description here

Visual Studio Code Environment For Laravel

Is their any specific configuration or technique which I can use to make these extensions work or there is some other way?

Kibler answered 17/9, 2017 at 19:44 Comment(0)
P
124
  1. First go to "Visual Studio Code" Settings and search for the option "files.associations" If that option is not available in your settings. Please update your Visual Studio Code to latest version.

  2. In the settings overwrite panel past the following snippet

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

It'll associate .blade.php and .tpl file extensions for html type

Save it and your are good to go. Happy formatting :)

enter image description here

Update: There are still some issues in formatting html with blade code, the formatter tend to bring blade code in a single line while executing format command. However, if your code grow that's won't be a problem. Moreover, you can easily manage those by putting a line comment in between your blade blocks. And commenting in code is always a good thing.


Update: Seems updated version adds an option to enable blade formatting in the user settings. To use that,

  1. Please make sure you are using the latest version and "Laravel Blade Snippets" Extension installed.

  2. Then Ctrl+Shift+P : type User settings : Enter

enter image description here 3. In "User settings" > "Extensions" > "Blade Configaration" check the option Enable format blade file.

enter image description here

That's it.

Press answered 9/3, 2018 at 0:17 Comment(3)
The blade formatter in the current version of laravel-blade-snippets will left align all blade directives and remove indentation, which makes nested blade directives hard to read. There are currently several issues open referencing this, including github.com/onecentlin/laravel-blade-snippets-vscode/issues/104Snubnosed
Doesn't it format js code inside the script tag in the blade files?Mcphee
SHIFT + ALT + F works now. Thank you. My only note is that you can find settings in File > Preferences > Settings I searched it a while.Waynant
B
36
  • Update your VS Code. Go to Settings>Extensions and Enable Blade Format checkbox.

Enable Blade code format

  • Restart VS Code for the changes to take effect.

  • Use auto-formatter Shortcut for Windows: Shift+Alt+F

Benedick answered 21/10, 2018 at 6:44 Comment(2)
That doesn't seem to work as November 19, 2019. I don't have any other 3rd party formatters enabled either. I even tried starting a new document. Basically, if I format the blade doc, it aligns all lines to the left. bummer.Trici
Also restart Visual Studio Code for changes to take effect.Admonition
M
16

UPDATE 2022: this extension may no longer be maintained.

For me, this extension works perfect for auto indentation with the following settings:

"beautify.language": {
        "html": [
            "blade",
            "html"
        ]
    },
Michelmichelangelo answered 7/5, 2019 at 3:13 Comment(2)
Can you describe where is option for beautify Extension SettingsPhytology
This settings snippet is intended to go in settings.json. You can get there by selecting "Preferences > User Settings", then look for a "Edit in settings.json" link under any of the settings shown from the menu. That said, at the time of this comment, Beautify does not format Blade templates correctly unless you implement the code @Slivicon posted.Decompound
I
15

First install this extension, https://marketplace.visualstudio.com/items?itemName=onecentlin.laravel-blade

Open settings.json. Add this lines.

"[blade]": {
    "editor.defaultFormatter": "onecentlin.laravel-blade",
    "editor.formatOnSave": true
}
Idolater answered 24/12, 2019 at 0:53 Comment(2)
The accepted answer didn't work for me - it kept trying to use Prettier in spite of me adding blade to ignored languages for that. This however, worked a treat.Jesher
This formatted my other non-blade html, breaking tags into new lines made it messyHierarch
D
9
Files>Preferences>Settings>Extensions>Blade Configurations

Then Enable format blade file (Follow Image).Then Restart Visual Studio Code.Now Use Shift+Alt+F To format. Now OK.

Dispassionate answered 4/6, 2019 at 9:35 Comment(0)
K
9

this solution works for me in 2021

First, install Laravel Blade after that update your settings.json file and add this section

"[blade]": {
  "editor.defaultFormatter": "amirmarmul.laravel-blade-vscode",
  "editor.formatOnSave": true
}
Kobylak answered 14/5, 2021 at 15:56 Comment(3)
Well, this works for me easy to use, and still works in 2023.Whenever
The current formater doesn't work. Had to change to this one: "editor.defaultFormatter": "onecentlin.laravel-blade"Goins
It's working for me after 5 mins of use and it doesnt do unwanted html formatting! github.com/amirmarmul/laravel-blade-vscode I had to uninstall onecentlinHierarch
C
8

Add these lines to your VS Code settings.json file after installing Laravel Blade Formatter extension:

https://marketplace.visualstudio.com/items?itemName=shufo.vscode-blade-formatter

"editor.formatOnSave": true,
"[blade]": {
    "editor.defaultFormatter": "shufo.vscode-blade-formatter"
},
Cyclothymia answered 15/8, 2021 at 0:16 Comment(0)
T
3

I would like to suggest vscode-blade-formatter for VSCode that support directive indentation and php code formatting in directives.

screenshot

This is based on my previous project blade-formatter. The motivation I created this is I wanna format blade files with correct indentation programmatically via CLI.

Try if you would like to indent directives.

Trave answered 24/7, 2020 at 6:57 Comment(2)
this looks good but how come its not on the VS Code Extensions Marketplace?Centrum
marketplace.visualstudio.com/… you can download extension from hereTrave
V
3

To use Blade with any extension that works with HTML use emmet.includeLanguages (Emmet Include languages) settings. Add item blade and value html.

enter image description here

    "emmet.includeLanguages": {
        "blade": "html" // Use HTML in Blade files
    },

Now HTML works in Blade associated files, you may use Blade and HTML snippets and other extensions.

enter image description here

enter image description here

enter image description here

Validate answered 10/5, 2022 at 8:31 Comment(0)
S
1

The only solution I've found that will actually attempt to indent blade directives mixed with html in a blade file is a hack for the beautifier javascript from the Beautify extension, done by Faizal Nugraha.

Edit: This doesn't appear to support formatting of blade directives inside an html <script> tag, though. Beautify seems to format that as JavaScript.

  1. Install the Beautify extension
  2. Edit ~/.vscode/extensions/hookyqr.beautify-1.5.0/node_modules/js-beautify/js/src/html/beautifier.js (Linux/MacOS) or %USERPROFILE%\.vscode\extensions\hookyqr.beautify-1.5.0\node_modules\js-beautify\js\src\html\beautifier.js (Windows) and do the following:
  3. Look for the function Beautifier.prototype.beautify = function().
  4. Inside the function look for the line var source_text = this._source_text;
  5. After that line, paste in:
        // BEGIN blade-1of2
        source_text = source_text.replace(/\{\{(--)?((?:(?!(--)?\}\}).)+)(--)?\}\}/g, function(m, ds, c, dh, de) {
        if (c) {
            c = c.replace(/(^[ \t]*|[ \t]*$)/g, '');
            c = c.replace(/'/g, '&#39;');
            c = c.replace(/"/g, '&#34;');
            c = encodeURIComponent(c);
        }
        return "{{" + (ds ? ds : "") + c + (de ? de : "") + "}}";
    });
    source_text = source_text.replace(/^[ \t]*@([a-z]+)([^\n]*)$/gim, function(m, d, c) {
        if (c) {
            c = c.replace(/'/g, '&#39;');
            c = c.replace(/"/g, '&#34;');
            c = "|" + encodeURIComponent(c);
        }
        switch (d) {
            case 'break':
            case 'case':
            case 'continue':
            case 'default':
            case 'empty':
            case 'endsection':
            case 'else':
            case 'elseif':
            case 'extends':
            case 'csrf':
            case 'include':
            case 'json':
            case 'method':
            case 'parent':
            case 'section':
            case 'stack':
            case 'yield':
                return "<blade " + d + c + "/>";
            default:
                if (d.startsWith('end')) {
                    return "</blade " + d + c + ">";
                } else {
                    return "<blade " + d + c + ">";
                }
        }
    });
    // END blade-1of2
  1. Look for the line var sweet_code = printer._output.get_code(eol);
  2. After that line, paste in:
    // BEGIN blade-2of2
    sweet_code = sweet_code.replace(/^([ \t]*)<\/?blade ([a-z]+)\|?([^>\/]+)?\/?>$/gim, function toDirective(m, s, d, c) {
        if (c) {
            c = decodeURIComponent(c);
            c = c.replace(/&#39;/g, "'");
            c = c.replace(/&#34;/g, '"');
            c = c.replace(/^[ \t]*/g, '');
        } else {
            c = "";
        }
        if (!s) {
            s = "";
        }
        switch (d) {
            case 'else':
            case 'elseif':
            case 'empty':
                s = s.replace(printer._output.__indent_cache.__indent_string, '');
                break;
        }
        return s + "@" + d + c.trim();
    });
    sweet_code = sweet_code.replace(/@(case|default)((?:(?!@break).|\n)+)@break/gim, function addMoreIndent(m, t, c) {
        var indent = printer._output.__indent_cache.__base_string;
        c = c.replace(/\n/g, "\n" + indent + printer._output.__indent_cache.__indent_string);
        c = c.replace(new RegExp(indent + '@' + t, 'gi'), '@' + t);
        return "@" + t + c + "@break";
    });
    sweet_code = sweet_code.replace(/\{\{(--)?((?:(?!(--)?\}\}).)+)(--)?\}\}/g, function (m, ds, c, dh, de) {
        if (c) {
            c = decodeURIComponent(c);
            c = c.replace(/&#39;/g, "'");
            c = c.replace(/&#34;/g, '"');
            c = c.replace(/(^[ \t]*|[ \t]*$)/g, ' ');
        }
        return "{{" + (ds ? ds : "") + c + (de ? de : "") + "}}";
    });
    // END blade-2of2
  1. Save the file and restart VS Code.

Of course this has to be redone if the file is changed, by an update or otherwise.

Ref. https://gist.github.com/fzldn/a27973ff7e4c8e3738b0e06e525f7403#gistcomment-2693197

Snubnosed answered 16/3, 2020 at 21:31 Comment(2)
Thanks for posting this! A long way to go for some simple formatting, but I think your solution is the only way to accomplish the correct indention.Decompound
I can't take credit, of course, for the code, that belongs to Faizal in the linked gist, but I have found it the best so far. There are still some limitations to it, but it's the best solution I've found so far.Snubnosed
E
1

You're left to your own devices in finding the right extension here. You would want to use an extension because it has more power than the built-in formatting.

For a long time I was using Laravel Blade Snippets because at the time of this message it has 1.4 million installs. However, I've recently swapped over to Laravel Blade Formatter and although only 134K installs, I'm much happier now.

Once you've found your poison, Control-Shift-i is your friend.

Endocarditis answered 17/8, 2021 at 8:40 Comment(0)
M
0

Add this in settings.json

"beautify.language": {
        "html": [
                "blade"
        ]
},
Machzor answered 12/7, 2020 at 8:47 Comment(0)
W
0

I tried Blade Snippet By Winnie but it has multiple issue. Recently I started using the below on and its working perfectly.

Name: Laravel Blade

Id: amirmarmul.laravel-blade-vscode

Description: Snippets, Syntax Highlighting, and Formatting for VS Code

Version: 2.0.4

Publisher: amirmarmul

VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=amirmarmul.laravel-blade-vscode

Weide answered 24/1, 2023 at 7:17 Comment(0)
O
-2

Right click anywhere in the document, select 'format document with' and than select laravel blade snippets. Install Laravel blade snippets extension first.enter image description here

enter image description here

Ovolo answered 15/6, 2021 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.