Javascript Templating with Django - javascript

I'd really like to use a Javascript templating system together with Django. The syntax and style of Mustache.js (and it's derivatives) really sits well with me. The problem is the delimiter tag used by Mustache doesn't play nicely with the syntax of Django's templating system.
Is there any good way to use them together?
I have tried using this verbatim snippet to render the JS templates properly. The problem with that solution is I still sometimes need Django variables or URLs inside the JS.
I have also tried changing the delimiter for Mustache using
{{=[[ ]]=}}
However, that doesn't allow for using section tags, like {{#}}. The author has said he intends on removing that capability in future releases altogether.
Are there any template libraries for Javascript that follow closely to Mustache.js, but use different delimiters? Or is there another solution for changing the delimiters Mustache.js uses?

I've used jquery's templating with django. Ultimately I decided the best way is:
put all the javascript into static javascript files and serve them up without any serverside processing
in the django templates deliver all the html hooks (id's or classes) but no js.
in the js use 'document.ready' plus jquery selectors to insert tags into the page and attach events
if the js needs data then make an ajax call.
I softened on the last one and might embed data as a block of json into the django template, and perhaps also have a short js at the bottom of a template which do no more than set variables/parameters to instruct the js how to render the page - little clues from the server side telling it what to do.
Thus:
contention between the escape characters becomes a non-issue
you don't have to keep asking yourself "is this code running on the server or on the client" because you're not trying to write both at once into the one file
your javascript code is necessarily better structured and re-usable

It looks like it would be extremely easy to change Mustache's delimiters, although configurable delimiters should be supported in my opinion.
If this is not acceptable to you, there are many other templating libraries out there such as jquery-tmpl and underscore.template.

EJS is a pretty nice templating system. It uses <% %> tags.
Edit: More templating libs

Related

How to outsource HTML Tags from JavaScript?

I am wondering how to separate JavaScript and HTML. Of course, i include JS with:
<script src="function.js"></script>
But when i add dynamically HTML-Tags to the website with JS like:
$( "#content" ).append("<h2>");
Then there are HTML Tags inside JavaScript Code. Can i make this modular or is there any "Good Practice" to do it?
Or should i use a framework like Bootstrap to code larger projects and exclude those frameworks the HTML Tags?
If you really want to separate your application logic from the layout, you should use a template framework. There are a lot of frameworks out there who do the job like:
Underscore
Mustache
Handlebars
and many more
What you essentially do is providing data objects to the template engine. Based on the logic you define in the template you render the page without the need to clutter the application logic and the layout.
In order to find the right template engine for your application you might want to check out: http://garann.github.io/template-chooser/ Here you can define what kind of engine you are looking for and the website shows you the most suitable library.
you can create a hidden template object, then .clone() it in javascript. Or use one of many MVVM / template javascript frameworks

Handlebars Template Management

This seems like a straightforward question, but my google-fu isn't working for me on this one.
After doing an ajax template load, how do we manage templates? Next time around I don't want to make a duplicate ajax call for the same template. Should I stick it in the dom under a <script type="text/x-handlebars"> tag? Throw it in an array? I see Handlebars supports a registerPartial function, but as I understand it, that's only for partials that are to be used in other templates... Can I register compiled templates and manually use them later? If so, how to check if they exist? What is the best practice here?
If you're using require.js, you can rely on the text or one of the handlebars template loader plugin.
If you're not very much into AMD (you should - but), then you could add precompilation to your build process via tools like grunt-contrib-handlebars.
These advice are mostly generic, you can checkout how we manage inlining templates over on the Backbone-Boilerplate

Client-side templates in script tags. Advantages/Disadvantages?

Just curious about the current trend to put client-side templates for single-page Java applications in script tags in your HTML file. Seems like an interesting approach, but is this considered a best practice (or at least a better practice)? I tried to come up with a list of advantages and disadvantages, but the list of bad seems to outweigh the good.
So the way I see it is this:
Advantages:
Only one request to get all templates vs. an individual async request for each template file.
Disadvantages:
Creates a potential merge troublespot / bottleneck file if all templates are in one location
A bit cumbersome to edit templates all in one file
A bit cumbersome to find the template you need vs. using a keyboard shortcut to open file.
Have to wait until the DOM is ready before doing anything with a template.
It also seems that with having them in script tags, you can precompile and cache your templates so you're only querying the DOM once to get each template. However, couldn't you achieve the same effect using AMD / Require and a require/text! or dojo/text!? In the latter instance, you'd be lazily loading each template only once. You could then cache it and precompile it at that point.
I just am struggling to see the many advantages of templates in script tags. Am I missing something?
IMHO it really comes down to how many templates you have. When your site is first starting out and you don't have a lot of templates, keeping them all in script tags on a single HTML page makes a lot of sense.
However, as your number of templates grows, that soon becomes unwieldy; before long you're using server-side logic to concatenate a bunch of separate template files in to your master HTML file, and at that point I think it makes perfect sense to start considering other approaches.
Personally my company's codebase started out with script tags in an HTML file, but as we've since grown (and started using require) and now now we have tens if not hundreds of .handlebars (or more commonly, .hbs) files for all of our templates. We bring these in to our Javascript using Alex Sexton's HBS plug-in (https://github.com/SlexAxton/require-handlebars-plugin) for require, and that works great because:
we get to use our standard require system for our templates
templates get compiled to a single compressed JS file when we use the require optimizer
we can configure our IDEs to treat .handlebars files as HTML, giving us the appropriate syntax coloring and such when we edit them
I'm not sure which templating system you're using, but if you're using Handlebars and already using Require then the HBS plug-in is a great way to. If you use a different templating system you likely can find a similar plug-in for Require (if that system is popular enough), or even write your own using the HBS one as a basis.
For anyone with a decent number of templates, I think a system like that (especially for anyone already using Require) makes a whole lot more sense than script tags.
If I understand you correctly, you have some number of client-side templates you want to use, but you would like to separate them into individual files on the server side. When you have a lot of such templates, there is some obvious engineering advantages to such an approach.
You might consider using JSONP. With a half-decent handler on the server side, you get the benefits you're looking for:
Separate file for each template
Easy inclusion into your HTML pages.
The ability to assign each template to a variable, or send it through a compilation function as soon as it is received by the client.
Cache templates on the client side, so they don't have to be reloaded for every page.
Compatibility with caching proxies
The only part of the JSONP implementation that is non-trivial is the caching properties. You need to make sure your server-side controller that receives the request understands conditional GETs, how to send 304 responses, and sets caching headers properly.
If you aren't familiar with the technique, you might take a look at the JSONP wikipedia entry.

What javascript/php template libraries will parse the same template files?

I originally was using Mustache.js but found that it does not work well for rendering large nested trees (it has no way of disambiguating variables of the same name in nested structures).
I was happy to find a PHP version of Underscore.js, but when I looked at the code of Underscore.php I realized that its template method does not render Underscore.js-style templates. Instead it replicates similar functionality but with PHP variables.
Jquery-tmpl/jquery-tmpl-php is another template language with JS and PHP libraries, but my concerns are that the jquery-tmpl-php library seems not to be used much (very few people are following it on github) and that jQuery decided to remove jQuery-tmpl as an official plugin: http://blog.jquery.com/2011/04/16/official-plugins-a-change-in-the-roadmap/
Also it seems that the author of jquery-tmpl has not touched it in months.
What are other people doing to render Javascript and PHP using the same templates?
Jade does it:
https://github.com/everzet/jade.php
https://github.com/visionmedia/jade
You should try mustache. It's has implementations in many different languages.
Have to get used to a different way to do control structures but its not too difficult to figure out.
http://mustache.github.io/

Are there templating systems that allow you to edit HTML, CSS and Javascript in the same file?

When you have a small HTML template, wouldn't it be nice to have the CSS and Javascript that relate to it (binding of events, etc.) in the same file right next to the HTML?
You could just put them in and tags, but normally you don't want to do this, because when you render the template many times you'll end up multiplying the code over and over again in the DOM. Besides, every respecting webdeveloper wants their CSS and Javasciprt in separate files.
But it's actually pretty simple to implement a system that goes through all your templates, removes all the tags with their contents and puts them into one big .css file and then the with contents to .js file, so that you can load them from separate files, and finally the tempalates are left with only HTML in them.
I'v done this and i'm still learning with the best practices on how to use it (eg. what parts of Javasript do you want to put there?), but it feels like the way i'd always want to develop web apps. So i'm wondering if there are any systems that use the same method.
Parsing HTML to remove duplicate tags as a standard practice seems wrong. Separating content, style and behavior should be a first class priority in any case. Why combine something just to rip it apart again? Imagine your CSS differs slightly among files. How does your parser know which one to keep?
IMO a proper templating approach for Javascript has a main HTML file, which is loaded using a HTTP request, which again links the CSS and JS for the rest of the application. This first file can as well link JS template files (like e.g. .jst) or these are loaded later on demand using an AJAX request. Nevertheless are these templates usually only containing structure, content comes from e.g. a JS model using a JSON connection to some kind of storage, "styling" is provided by the previously loaded CSS files.
Related: backbone.js and sammy.js

Categories

Resources