Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run JSHint on files with Django template markup in them?

I would like to run JSHint on all my Javascript source files but several of them have some embedded Django template markup. JSHint throws a ton of errors on this markup.

Is there a way to either...

  1. Tell JSHint to ignore this markup
  2. Run the Djnago template parser with some dummy data to generate all permutations of the rendered js file and then run JSHint on that?

I assume I could write a bunch of code to do #2 but i'm wondering if there's an easier way.

like image 528
Fraser Graham Avatar asked Mar 26 '12 17:03

Fraser Graham


People also ask

How to enable templates in Django?

In Django, since we are keeping all the front end files separate from the back-end, these Text files (mostly HTML files) are also kept in a separate folder. Now if we go to the settings.py, there will a TEMPLATES option as shown above.

How to use Django’s built-in method render to render a template?

We are using the Django’s built-in method render which acts as a bridge between static HTML and Python. The render function takes three required arguments render (<em>request</em>, <em>template_name</em>, <em>context=None)</em> Save the files and run the server.

How to include snippets in Django templates?

Including snippets in a template is very simple. We use the includes keyword provided by Django’s templating engine. Go ahead and modify index.html to this:

How to create a simple static app in Django?

On that note, let’s add two folders inside the static folder to hold our files, one called css and the other called js. Inside css, create a file called main.css. Add a main.js in the js folder as well. Your static folder should now look like this: Once that is done, let’s create a new Django app called example that we will be working with.


2 Answers

Depending on a 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" %}

The only thing is that you have start script.js with a blank line—otherwise // will eat the first legitimate line of JavaScript code you have there. I wrote a simple helper {% includejs %} that does that for me automatically.

like image 55
Anton Kovalyov Avatar answered Nov 09 '22 11:11

Anton Kovalyov


Actually there is a canonical way to hide Django markup (or any other content) from JSHint:

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

The same for JSLint would be:

/*ignore jslint start*/
javascript_var = {{ context_json_string_var }};
/*ignore jslint end*/
like image 36
jammon Avatar answered Nov 09 '22 12:11

jammon