【问题标题】:Python formatting in VSCode ruins Django templatesVSCode 中的 Python 格式化破坏了 Django 模板
【发布时间】:2022-01-03 19:02:51
【问题描述】:

我正在编写一个 Django 应用程序,我在 VSCode (settings.json) 中使用以下配置来自动格式化我的 Python 代码(我也使用 Django VSCode 扩展):

{
    "liveshare.authenticationProvider": "GitHub",
    "editor.fontSize": 16,
    "files.trimFinalNewlines": true,
    "files.trimTrailingWhitespace": true,
    "files.insertFinalNewline": true,
    "html.format.endWithNewline": true,
    "files.exclude": {
        "**/__pycache__": true
    },
    "explorer.confirmDragAndDrop": false,
    "editor.formatOnSave": true,
    "git.confirmSync": false,
    "window.zoomLevel": -1,
    "python.linting.flake8Enabled": true,
    "python.formatting.provider": "black",
    "python.linting.flake8Args": [
        "--ignore=E501,E266,W503"
    ],
    "files.associations": {
        "**/*.html": "html",
        "**/templates/**/*.html": "django-html",
        "**/templates/**/*": "django-txt",
        "**/requirements{/**,*}.{txt,in}": "pip-requirements",
        "*.html": "django-html"
    },
    "emmet.includeLanguages": {"django-html": "html"},
}

虽然 Python 文件中的格式按预期工作,但它似乎也干扰了我的 Django 模板并破坏了它们。

比如下面这个模板……

{% extends "base.html" %}

{% load martortags %}

{% block title %}MyBlog - {{ object.title }}{% endblock title %}

{% block content %}
<ol>
{% for post in object_list %}
    <li>
        <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
    </li>
{% endfor %}
</ol>
{% endblock content %}

...保存后变成这个:

{% extends "base.html" %} {% load martortags %} {% block title %}MyBlog - {{
object.title }}{% endblock title %} {% block content %}
<ol>
  {% for post in object_list %}
  <li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
  {% endfor %}
</ol>
{% endblock content %}

settings.json 中所见,我尝试按照 Django VSCode 扩展文档中的说明进行操作,但没有成功。事实上,无论"files.associations""emmet.includeLanguages" 设置是否存在于settings.json 中,都不会发生任何变化。

如何将.py 文件格式(VSCode 正确识别为Python 文件)与.html 文件格式(VSCode 正确识别为Django Template 文件)解耦,并为后者使用普通的 HTML 格式化程序?

【问题讨论】:

    标签: python django visual-studio-code django-templates


    【解决方案1】:

    Python 的black 格式化程序不会格式化.html 文件。

    我不确定您为.html 文件选择了哪种格式。你可以看看User settings.json试试这个:

      "[html]": {
        "editor.defaultFormatter": xxx
      }
    

    您可以右键单击编辑器并选择Format Document with 以找出导致它的格式。 Prettier Code formatter 扩展看起来可能会导致它。

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2015-12-19
      • 2014-09-07
      • 2012-02-25
      • 2011-08-22
      • 1970-01-01
      • 2019-05-14
      • 2013-10-02
      • 2013-03-05
      相关资源
      最近更新 更多