Skip to content

[FEATURE] Format JSON and JS inside html attributes #1336

@oliverhaas

Description

@oliverhaas

Prerequisites

Feature Request

I occasionally encounter JSON and JS in html attributes, and currently djlint will just put all the code in a single line. I hate disabling the formatter for some blocks, and some templates became quite unreadable...

So, I gave the topic a shot to implement something which would format these kind of JSON/JS attributes. The PR already exists #1337 and I'm hoping for some feedback.

My implementation will turn this

<span x-init="date = new Date(); setTimeout(() => {  foo = false;}, 3000);"
              x-data='{ foo: true, baz:             false                   }'
              class="hs-tooltip-content"
              role="tooltip">{{ error }}</span>

into this

<span x-init="date = new Date();
              setTimeout(() => {
                  foo = false;
              }, 3000);"
      x-data='{
                  foo: true,
                  baz: false
              }'
      class="hs-tooltip-content"
      role="tooltip">{{ error }}</span>

Note that this is obviously a minimal example, and the minimal length and number of properties of the attribute's content when the new formatting will take place is configurable.

Issue #723 is related, since alpine js basically uses JS in html attributes. The default settings will actually cover alpine js attribute names (x-*).

Since the use of this feature is completely optional and disabled by default, it wouldn't hurt to merge the PR either such that more people can easily test it and give feedback. The PR could probably be cleaned up a bit, but overall everything I had in mind is there. Also, I'm using the already included jsbeautifier for JS and vanilla python for JSON formatting, mostly with the existing config options, so it's not a major change to the project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions