Use same Handlebars template for all the pages - javascript

I have this use-case where I would like to have one navbar for all the pages. The technique which I used until now was to keep an external JSON file and fetch it using jQuery .getJSON library. I was using jQuery DOM methods to generate the HTML.
That I am finding messy and would love to use Handlebars template instead. But my doubt is, in Handlebars you add script within script tag inside the HTML. So is there a way to just write an individual Handlebars template and invoke it on all the pages?
I have done some searching and couldn't find anything. I am just asking if I can embed Handlebars template like that or I do have to explicitly embed for all the pages for which I need the navbar? In other words, can I add Handlebars template inside a xyz.js file.

Short answer is: yes you can. You can either precompile your templates to one JavaScript file and insert them to your document with JavaScript, by using a partial or with a hybrid method such as this one by Tal Bereznitskey, that makes it possible to mix and match precompiled and uncompiled templates.

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

Javascript Templating with Django

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

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

Django - Template tags in javascript and css files

Is there any way to add template tags into javascript and css files? I would use it for anything from passing in urls to media url links (image paths, etc) to conditional javascript based on user permissions.
I just had a thought that maybe I can serve it up as if it were a template but have the url as my javascript file. Is that the only way to do somethign like this? If so, it probably wouldn't work with my media generator, so I'd probably want a better solution if there was one out there.
How about defining the JavaScript variables and CSS attributes from within your Django HTML template, between script and style tags? I know it sounds like a hack, but it seems to me a tidy one, as this will allow you to control your dynamic variables from one spot.
Your idea is the right way to go. If you want to leverage Django's template tools then the easiest way is to serve up the JS file as a template. See this question for a situation like yours.
You can serve any type of content like a template, it doesn't have to be HTML. However, you may not be able to serve it with the rest of your static content, depending on your setup.
One option, if you only want to replace things like media URLs, is to "compile" these templates into static files that you can serve. This won't work for anything that is conditional based on the current user's permissions, though. You'll need to write a script to call django.template.loader.render_to_string and write the result to a file every time you deploy or change media URLs, etc.
As for dynamic content inside JS-files, you would have to make a template, like the others said.
But you can very easily attach JS and CSS files to specific page templates using django-sekizai. (I use it as a part of django-cms, but it works stand alone too.)
It allows you to, inside a normal page template, define the template's required static resources in a block. There is one block for CSS and one for JS. These blocks can then be printed in your base.html. It also handles duplicates, so you don't have to worry about adding the same files multiple times. See the usage document.
With this system, you wont be sending any restricted JS or CSS, since django will only run authorized templates, and the content will never be added to the JS and CSS blocks.

Categories

Resources