How to run JSHint for Django template markup files?

I would like to run JSHint in all Javascript source files, but some of them have built-in Django template markup. JSHint throws a lot of errors on this markup.

Is there any way ...

  • Tell JSHint to ignore this markup
  • Run the Djnago template parser with some dummy data to generate all permutations of the processed js file and then run JSHint on this?

I suppose I can write a bunch of code to do # 2, but I'm wondering if there is an easier way.

+5
source share
5 answers

Depending on the markup, you can get away with "hiding" Django markup with JavaScript comments. We do this, for example:

// {% if cond %}
someJavaScriptCode();
// {% else %}
somethingElse();
// {% endif %}

// {% include "script.js" %}

, script.js , // JavaScript, . {% includejs %}, .

+3

Django ( ) JSHint:

/* jshint ignore:start */
javascript_var = {{ context_json_string_var }};
/* jshint ignore:end */

JSLint :

/*ignore jslint start*/
javascript_var = {{ context_json_string_var }};
/*ignore jslint end*/
+2

. jslint , "stuff =" .

var stuff;
/* {{ '*' + '/' }}
stuff = {{ variable_containing_json_object_or_list }};                      
// */
+1

, --extract . HTML-, .

jshint --extract=always your_template_file.html
+1

javascript- django jslint:

They can be easily hidden in javascript comments, just as Anton Kovalev suggested:

// {{ if some_flag }}
console.log("Conditional log");
// {{ endif }}

String variables

The obvious solution is to include the django tag in double quotes. However, it is worth remembering that the generated code may be invalid if the contents of the variable are not properly escaped:

var javascript_var = "{{ context_var|escapejs }}";

Complex structures serialized in json

Edwin's trick works:

var javascript_var;
/* {{ '*' + '/' }}
javascript_var = {{ context_json_string_var }};                      
// */

If you included the original javascript template in the html template, you can declare the getter function here and access it from the javascript script:

<script type="text/javascript">function getIt() { return {{ context_var }}; };</script>
<script type="text/javascript">{% include 'script.js' %}</script>

In that case, the javascript source would look pretty acceptable:

/*global getIt*/
var haveIt = getIt();
0
source

All Articles