djlint / djLint

✨ HTML Template Linter and Formatter. Django - Jinja - Nunjucks - Handlebars - GoLang
https://djLint.com
GNU General Public License v3.0
686 stars 84 forks source link

[BUG] [Formatter] broken formatting: format_css & format_js with template tags inside script & style blocks #809

Closed oliverhaas closed 8 months ago

oliverhaas commented 8 months ago

System Info

Issue

When using template tags inside either a script or style block, the formatter performs nonsensical formatting. image

How To Reproduce

Just enable format_css and format_js, use a template tag inside a script or style block, and format with djlint. Online demo also works as seen above.

Remarks

I realize there usually are reasons to not end up with code like above, but in general I think djlint should be able to format template tags inside style and script. The workarounds I have is turning off formatting for js and css completely, or not using template tags. Disabling formatting only partially usually breaks formatting in other ways. image

Let me know if I can be of assistance in some way.

oliverhaas commented 8 months ago

Ok, this is a bit embarassing, but I missed a couple of important points:

Formatting js with template tags works if one sets the proper templating parameter for the underlying js-beautify, e.g. in my pyproject.toml:

[tool.djlint.js]
templating = "django"

Maybe this should be the default when the djlint profile "django" is selected, but I just plain missed this on my end.

Formatting css runs into the problem that the underlying css-beautifier does not seem to support the templating parameter. Here is the related issue https://github.com/beautifier/js-beautify/issues/1979. So the cleanest solution I've found for css is to use the css-beautifier ignore syntax.

<style>
  /* beautify ignore:start */
  {% whateverTemplateTagWeWantToIgnore %}
  /* beautify ignore:end*/
</style>

which is obviously not ideal.

I think these are good (js) and okay (css) solutions, and nothing really can be done on the djlint-side, so I'll close this issue.

Ehco1996 commented 7 months ago

I've encountered this issue as well, and I concur with @oliverhaas's suggestion that setting the default template value to Django when formatting CSS and JS is a better approach.