Formatting php with html

Как отформатировать файлы PHP с разметкой HTML в коде Visual Studio?

Я использую Laravel, поэтому все мнения .blade.php файлы. Visual Studio Code не будет форматировать HTML из-за расширения PHP. Я удалил часть лезвия имени файла, но он все еще не форматирует файлы должным образом (через Alt + сдвиг + F ).

Я также попробовал около пяти расширений, но ни одно из них не выполняет переформатирование.

Как я могу отформатировать .blade.php файлы в коде Visual Studio?

Решение

Расширение beautify просто делает это очень хорошо, либо добавьте php и любой другой тип расширения файла в конфигурацию, как сказано выше, вот пример:

  1. перейти в настройки пользователя (CTRL + запятая)
  2. найдите beautify в приведенном выше поле и найдите строку beautify.language, затем щелкните левой кнопкой мыши на значке карандаша и нажмите «заменить» в настройках. Это добавит конфиг справа (пользовательские настройки).
  3. для раздела html просто добавьте php и blade.php

введите описание изображения здесь

ИНАЧЕ: Вы также можете сделать это напрямую, тип F1 затем написать украшать, автозаполнение дать вам два варианта украсить выбор или же украсить файл. Выберите тот, который вам нужен, и это сделает работу. это прямой прямой путь.

Читайте также:  Про мышей

введите описание изображения здесь

Вы также можете добавить KeyBinding иметь Сочетание клавиш, вот как это сделать:

  1. открыть keybindings.json (перейти файл> настройки> сочетания клавиш)
  2. нажмите выше, откройте и измените keybindings.json
  3. добавить следующее в закрытые скобки [] «ключ»: «alt + b»,
    «команда»: «HookyQR.beautify»,
    «когда»: «editorFocus»
    >

выберите любой ключ, который вы хотите, и убедитесь, что вы не переопределяете существующий, ищите сначала слева, если он существует или нет.

введите описание изображения здесь

обратите внимание, что все эти вещи хорошо документированы в описании расширения.

Другие решения

Я думаю украшать может сделать трюк. Просто добавьте «php» и / или «blade.php» в раздел HTML своей конфигурации, чтобы украсить файлы просмотра PHP / Blade. Работает для меня!

украшать действительно решает эту проблему! Многие люди добавляют «blade.php» и «php» в конфигурацию HTML. Beautify не распознает и вручную выбирает шаблон HTML. Вместо этого просто добавление «лезвия» в конфигурацию HTML решает все проблемы.

Если вы хотите что-то, что просто работает, добавьте формат вложенного HTML в файлы PHP, поддержка vscode уже должна быть.

Использует все собственные настройки html.format, формат при сохранении и т. Д. Дайте расширение Формат HTML в PHP попытка Я сделал это, потому что любое другое решение раздражало меня, потому что оно не работало на 100%.

я нашел это расширение называется Формат HTML в PHP это хорошо работает для меня.

Источник

PHP formatter

PHP formatter

In every programming language, we have a code structure that we need to follow, which maintains the readability of the code to other developers. This is something called coding standard in general. Like other programming languages, we have many tools available online where we can format our code by applying some styles to them. Formatter is nothing but used to format our code, making it easy to understand and readable by the new programmers by following the coding standard of language. In this topic, we are going to learn about PHP formatter.

Web development, programming languages, Software testing & others

How does PHP formatter work?

As we know, we know that formatter is used to format our code, and online we can find many formatters. We can either use a visual studio for this or any online formatter which provides good support for PHP. First, we will see how we can format our code using visual studio and what setting do we need to make this.

Visual Studio

Visual Studio provides good support for PHP where we can format our code by applying some style, but for this, we need to make some settings into it. By using it, we can perform bracket matching of methods or classes; we can also highlight syntax, remove extra space, and align the code where needed. In addition, it will force us to follow the proper indentation and make our code look more beautified and presentable to others.

The visual studio uses the PHP linter to provide the improvement. But to use this, we have three different kinds of settings to control the liner of PHP :

  • php.validate.run: This setting will trigger the validation on the save of any file inside Visual Studio. The means once we save the file, then it will start validating. We can disable this setting as well, but its default value is onSave only. It can trigger validation on typing od code or on saving of the file. In most of the editors, it is typed only.
  • php.validate.enable: This key we can say enables the linter, and if we check, this is enabled by default in the editor.
  • php.validate.executable.path: This key checks that wheatear the executable of PHP is on disk or not. It keeps on monitoring that.

In visual studio, provide some of the available snippets for PHP to check this; we have a short-cut key ctrl+space like any other editor where we can see the available options.

Like the visual studio, we have many other formatters available for PHP. Now we will talk about the online formatted, which can be easily used just by copy-paste the code.

http://www.phpformatter.com/ – This is the online available formatter for better understanding. I am attaching a screenshot of this formatter. See below;

PHP formatter output 1

As we can see here, this formatter provides us with three options here to format our code based on various parameters. Let’s discuss each of them in detail:

1. input: This is the input parameter that takes the input and gives us some output. This input basically our code which we want to format according to a coding standard. Like it will remove unnecessary spaces, unused packages, if any, and many more options available. So in the section, we will just be going to copy-paste the code that we want to format.

2. Style: As the name suggests, it gives, or we can say, add style to our code or file and arrange its proper format. In this section, we can select different types of styles for our code. Like see below ;

  • Indentation style: There are different types of style available some of them are mentioned below;
  • Starting Indentation: In this block, we can give an integer value.
  • Indentation: In this block, we can give value as an integer by default for PEAR style; it is 4.

Apart from this, we can perform many things like on brackets, switch operations, functions, highlight keywords, and many more.

3. Output: This is the last tab that is available, and it basically shows us the output. It will contain all the styles that we have applied for a particular piece of code while doing the formatting of it. So from here, we can copy our code and place this into our workspace without any additional settings.

We can download some extensions from the visual studio marketplace to format our code as needed. We can also use one short key for this (ctrl + shift + X); this will give the list of all the available extensions. We just need to filter them out based on our key. For example, just type in ‘PHP’, and you will see a list of all extensions and add them to your workspace.

The list of extensions available in the visual studio is as follows to format our code :

Code runner Prettier HTML CSS support
PHP IntelliSense

Examples of PHP formatter

Given below are the examples of PHP formatter:

Example #1

In this example, we are using the PEAR style to format our code. In the output, you will some highlighted code as well with proper space in between.

   

demo for formatting PHP code

PHP formatter Example 1

Example #2

In this example, we are using different styles to format the code. Also, we are removing all the comments from the code. So in the actual program, you will see the comment, but you will not see the comment in the formatted program. This is very quick.

   

demo for formatting PHP code

Using different styles

Uses of PHP formatter

  1. Formatter very much needs to understand the code.
  2. It makes our code very much readable.
  3. We can highlight the main keywords by using this so that it will increase visibility as well.
  4. We can remove unnecessary comments and spaces from the program. We do not need to do this for each file and remove each line; it will automatically do this for us.
  5. We can also remove the empty lines from the code.

Conclusion

In PHP, we have many formatter available; also extensions from the visual studio are there. If you want to follow an easy-going approach, then we can use any online formatter by just copy-pasting the code. It makes our code looks very beautiful and professional.

This is a guide to PHP formatter. Here we discuss the introduction and working of PHP formatter along with examples and code implementation. You may also have a look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Basically this vscode extension uses all your standard configurations for html formatting, and your standard configurations for format on save, etc. It more or less works exactly how vscode should already work as it pertains to HTML in PHP files.

License

RiFi2k/format-html-in-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Formatting for the HTML code in PHP files.

This extension provides formatting for the HTML code in PHP files. This way this works is this extension runs right before the save action which triggers any other registered PHP formatting extensions so you are free to have one and this will not get in the way or block it.

Supported Features

  • Uses VSCode configurations for HTML formatting
  • Uses VSCode format on save setting
  • Custom keybinding for anytime formatting
  • Right click context menu option on PHP files
  • Command Palette option for formatting

There are multiple issues and Stackoverflow posts about not being able to format the HTML in PHP files and none of the solutions proposed anywhere really worked 100% so I decided to fix it.

Issues, Ideas, Feature Requests? Go ahead and add them. I’m down to help, add, or fix anything because I know this is badly needed for a lot of PHP / WordPress devs and was a major annoyance for me.

Feel free to have nested HTML in .php files now, it will format as you are expecting.

CTRL + ALT + F

You can change this if desired through the standard Keyboard Shortcuts (File > Preferences > Keyboard Shortcuts) option screen the name is «Format HTML in PHP».

Within a PHP file you can right click and there is a menu option to Format HTML in PHP.

Turn on format on save either globally or scoped to PHP.

"editor.formatOnSave": false, "[php]": < "editor.formatOnSave": true >

Here is the list of native vscode settings I pass to JS Beautify which control how your HTML will be formatted. You can change any of these to configure how the HTML will be formatted.

"editor.insertSpaces": true, "editor.tabSize": 4, "html.format.contentUnformatted": "pre,code,textarea", "html.format.endWithNewline": false, "html.format.extraLiners": "head, body, /html", "html.format.indentHandlebars": false, "html.format.indentInnerHtml": false, "html.format.maxPreserveNewLines": null, "html.format.preserveNewLines": true, "html.format.wrapLineLength": 120, "html.format.wrapAttributes": "auto",

Источник

Оцените статью