djlint / djLint

✨ HTML Template Linter and Formatter. Django - Jinja - Nunjucks - Handlebars - GoLang

Home Page:https://djLint.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

oliverhaas opened this issue · comments

  • I'm on the latest version of djLint
  • I've searched the issues (template tags, css, js, format_css, format_js, script, style, ...)
  • I've read the docs

System Info

  • OS: Ubuntu 22.04
  • Python Version: 3.11
  • djLint Version: 1.34.1
  • template language: django html

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.

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 beautifier/js-beautify#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.

commented

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.