Javascript Templating with Django

I would really like to use the Javascript template system with Django. The syntax and style of Mustache.js (and its derivatives) really goes well with me. The problem is that the separator tag used by Mustache doesn’t work well with the syntax of the Django template system.

Is there a good way to use them together?

I tried using this verbatim snippet to display JS templates correctly. The problem with this solution is that I still need Django variables or URLs inside JS.

I also tried changing the separator to Mustache using

{{=[[ ]]=}} 

However, this does not allow the use of section tags, for example {{# #}. The author said that he intends to completely remove this feature in future releases.

Are there template libraries for Javascript that keep a close eye on Mustache.js but use different delimiters? Or is there another solution for changing separators Mustache.js uses?

+4
source share
3 answers

I used jquery templating with django. I eventually decided that the best way:

  • puts all javascript in static javascript files and serves them without server processing.
  • in django templates all html hooks (id or classes) are delivered, but not js.
  • in js use "document.ready" plus a jquery selector to insert tags into the page and add events
  • If js needs data, then make an ajax call.

I relented on the latter and could insert the data as a json block into the django template and possibly also have short js at the bottom of the template that do nothing more than set variables / parameters to instruct js how to render the page - small server side hints saying what to do.

In this way:

  • Conflict between escape characters becomes a non-issue
  • you don’t need to constantly ask yourself: “this code works on the server or on the client”, because you are not trying to write both files to one file at once.
  • your javascript code is necessarily better structured and reused
+4
source

It seems like it would be very easy to change Mustache separators , although custom separators should be supported, in my opinion.

If this is not acceptable to you, there are many other template libraries such as jquery-tmpl and underscore.template .

+3
source

EJS is a pretty nice template system. It uses the <% %> %% <% %> tags.

Edit: Other libs templates

0
source

All Articles