rtts / djhtml

Django/Jinja template indenter
GNU General Public License v3.0
571 stars 32 forks source link

djhtml is not indenting javascript code if not surrounded by script tag #121

Open marcodicro-dp opened 1 month ago

marcodicro-dp commented 1 month ago

I have a shell html template that other templates extend from.

In the shell template I have this:

<script type="text/javascript">
  {% block js_includes %}{% endblock %}
</script>

That way, I don't have to include the script tag in every template that extends from the shell.

However, when I run djhtml over those files, the javascript code is not properly indented:

{% block js_includes %}

  $(document).ready(function() {

  $('input:radio[name="reason"][class~="radio-ext"]').change(function (e) {
  var $el = $(e.currentTarget);

  $('input:radio[name="reason"]').each(function(){
  if ($el.attr('id') != $(this).attr('id')) {
  $(this).next().next().addClass('hide');
  } else {
  $(this).next().next().toggleClass('hide');
  }
  });
  });
  })
{% endblock %}

It is properly indented if I add surrounding script tags:

{% block js_includes %}
  <script type="text/javascript">

    $(document).ready(function() {

      $('input:radio[name="reason"][class~="radio-ext"]').change(function (e) {
        var $el = $(e.currentTarget);

        $('input:radio[name="reason"]').each(function(){
          if ($el.attr('id') != $(this).attr('id')) {
            $(this).next().next().addClass('hide');
          } else {
            $(this).next().next().toggleClass('hide');
          }
        });
      });
    })
  </script>
{% endblock %}

How could we fix/workaround this? Can the script tag not be mandatory to properly indent js?

marcodicro-dp commented 1 month ago

Could we have {# fmt:js_on #} and {# fmt:js_off #} options to force toggle js mode?

aci2n commented 1 month ago

I am giving this a shot in https://github.com/aci2n/djhtml/commit/cfa92508ccd81b7082fd8f9e16bb91a18d82bce0 :D

JaapJoris commented 1 month ago

Since this is a similar problem to #110, I would like to repeat the comment that I made there:

Unfortunately, I have to conclude (https://github.com/rtts/djhtml/issues/103#issuecomment-1756111119) that supporting a {# fmt: #} tag is hard without running into inconsistencies in the InsideHTMLTag mode. It's the most complicated (read "hacky") mode in DjHTML, but I like the way it currently performs and I don't want to change it.

It is feasible to implement {# fmt:mode #} inside all modes except that one, though. However, it would not be consistent (read "fair") to support {# fmt:mode #} in some places and not in others, so I'd rather not support it at all. After all, there already exists {# fmt:off #} and {# fmt:on #} as an "escape hatch" for all cases that DjHTML doesn't support.

However, if someone manages to get it to work (including test coverage), I'll of course be happy to merge the PR!