Skip to content

Approach to client side templating (Handlebars.js)

Radina Matic edited this page Aug 5, 2015 · 5 revisions

For client-side templating, we use Handlebars.js.

Templates are written as separate .handlebars files, inside a (subfolder of a) folder in Django apps called "hbtemplates". The templates are then bundled into "modules" (based on the subfolder name) that can be loaded for use on the client side.

E.g. (if your module name is modname):

  • Create a template file in kalite/main/hbtemplates/modname/my-template.handlebars
  • Add <script src="{% url 'handlebars_templates' module_name='modname' %}"></script> in your template, to load the module with all its templates
  • Reference the executable template with var my_template = HB.template("modname/my-template")
  • When you want to render your template, just run it as a function, passing in a context object, e.g. var my_html = my_template({name: "Sally", age: 43}).

For an example, and to see how we use this within Backbone.js, see the code in: https://github.com/learningequality/ka-lite/pull/2313/files

Conditions in .handlebars files

For examples on how to use conditions in your handlebar files, see the code here:
https://github.com/learningequality/ka-lite/blob/develop/kalite/coachreports/static/js/coachreports/student_progress/hbtemplates/playlist-progress-details.handlebars

For list of logical operators available, check the helper function inside handlebars.js file:
https://github.com/learningequality/ka-lite/blob/develop/kalite/distributed/static/js/distributed/base/handlebars.js

Good SO discussion with samples: http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional

Clone this wiki locally