Server-side rendering of handlebars.js templates with Django - django

Is it possible to render handlebar templates with Django? I am trying to avoid providing two copies of each template that needs to be rendered both server-side and client-side.

You want djangobars. Solves your problem quite nicely.

I've created a custom tag that solves this problem. It iterates through the parser and ignores the handlebars expressions when sandwiched in between {% handlebars %} and {% endhandlebars %}
Check it out: https://github.com/anthonysutardja/Django-Template-Handlebars

Related

Return html file without rendering in django

I want to use Django with single-page js framework and Django variable braces {{ clashes with framework delimiters. So I need to return some html file like response in my view without rendering file with any context.
I've seen that many developers make reconfiguration of delimiters in JS but may be there are more suitable approach to save Django routing?
Put the desired code between {% verbatim %} and {% endverbatim %}. This will prevent Django from rendering it. You can read more in official documentation.
It is much better to remove template rendering from this altogether. From the point of view of Django, your JS framework's templates are static files, and they should be served as such.

Use Django templates to generate forms

I’m planning to use the Django templating system in a slightly uncommon way. I need an app that will let me easily create simple “fill in the gap”-style forms and I decided to use Django templates with custom tags to design the forms.
Here is a sketch of what I mean:
<p>
This is the <i>form</i>. Two plus two is {% gap four 4 vier %}.<br>
The best programming language is {% case_gap Python Haskell %}.
</p>
{% if all_correct %}
You are smart.
{% else %}
<input type="submit">
{% endif %}
The idea is that the *gap tags render a text input control, look into the context to see if the answer for them was sent, and if the answer is correct, mark the text inputs green.
The question is how to implement the all_correct logic. The simple solution is to add this variable to the context and then make each *gap tag update it based on its correct answer, and, I believe, this should work with my example. But what if I want to move the {% if all_correct %} code to the top of the template, where none of the gaps were rendered, and thus none of them have validated their answers yet?
Looks like I need some way to iterate over all the *gap tags before starting to render the template and [ask them to] validate the answers, but I don’t know the internals of the templating system well enough to implement this. Or there might be a completely different and better way.
I believe I figured how to do this after reading Chapter 9 of The Django Book.
Creating of a custom template tag involves defining of two things: how to compile the tag and how to render it. The compile-function should parse the tag data and return a Node—basically a thing that has a .render(self, context) method and some other data derived from the tag text.
The solution is to create FormNode—a subclass of Node that will also have a .validate(self, context) method. Then our custom tag will be compiled to a subclass of FormNode that implements validation logic.
The next thing to do is to create FormTemplate—a subclass of Template with a super-power: before starting to render individual nodes it will validate all the nodes by iterating over them and calling validate(context) on all the subclasses of FormNode and it will set the all_valid variable in the context.
Here is my proof-of-concept implementation: https://github.com/kirelagin/django-template-forms. I believe it works pretty well.
I used the ability to instantiate a custom template engine, which was added in Django 1.8. Overall, I had to dig a little deeper than one might expect and I always had this feeling that splitting of the templating API and the django engine (which is now just one of the available backends) wasn’t complete yet. I hope that Django 2.0 will bring us new cool stuff and all the hacks I had to add will vanish.

Combining Django Templates and Polymer

I've been stuck for the past few hours trying to figure out why the core Polymer elements are not being displayed properly in a Django application I'm making to act as a personal webpage. The application at the moment just points to an index.html page which, if you follow the tutorial on Polymer, is up to step one.
However, the components are not loading on my page. The static files are all set up correctly, and there's subtle animation from the css files being loaded correctly, but the Roboto font and the core-elements are not being displayed. Running the site as a normal HTML file does everything correctly.
Is there a specific way to user Polymer in a Django template?
Thanks.
See Eric's answer to this on the polymer-dev mailing list: https://groups.google.com/forum/?fromgroups=#!searchin/polymer-dev/django/polymer-dev/N2R8qknalOI/58ZhC1gWFh4J
Relevant excerpt:
Django 1.5 has support for the verbatim tag. You can wrap your inlined element definitions in that:
https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#verbatim
Example code snippet:
{% verbatim %}
<template repeat="{{item as items}}">
<my-element name="{{item.name}}"></my-element>
</template>
{% endverbatim %}
<script>
document.querySelector("template').model = {{items}}; // items here is filled by the server's template.
</script>
I'm pretty sure this has to do with the fact that Django uses the same {{}} in its templates as Polymer.
I'm adding this answer as a compliment to the already accepted answer.
You can force django to require a space for it's template tags. So for any django template tags you have to use {{ variable }} and for polymer you will use {{variable}}.
Here is a very simple module/app I created to "prepare" django for use alongside polymer.
https://github.com/andrewebdev/django-ostinato/blob/2c435dea23319be6e9011e7381afca2b4092b5a2/ostinato/polyprep/init.py
Credit goes to https://github.com/nebrybledu for this suggestion.

Subrequests in Django templates

I'm working on my first Django project and have my templates setup with a base that all the others extend. In that base I want to have some user-specific navigation which means loading some values from the database to build the contents of a drop down menu. However I don't want to have to do this inside each view. Coming from Symfony2/Twig I would normally do this using a sub-request where I tell the template to render a view and that will use it's own template. Using syntax like:
{% render 'Bundle:Controller:action' with {} %}
How would I accomplish this same thing with Django? I've read over the docs a couple of times but can't find any way to do this.
You have two approaches:
(better)
- add the code to base.html (the one you're always extending) and only override it when you need to.
or
(worse)
- in every template use {% include %} to include your menus.html template.
Update: re-reading your question: you could modify the request in context-processor so your base.html would then have this information.
Custom template tags are what you want.

How to call controller function from template in Django?

How to call controller function from template in Django instead of hardcoding URIs?
I guess You mean "link to it".
This can be done via {% url %} tag, see docs
If Your intent is to call view function directly, this is not possible by design - templates should not know about views, it's a separate layer.
How to call controller function from template
Not sure what you mean here. If you mean to provide an an HTML link to it see the second part of my answer below.
instead of hardcoding URIs?
In case you haven't already, use the {% url %} tag. Use this in conjunction with named URLs in your url config.
If you mean adding URL to the resulting HTML, then either use {% url %} tag as others, or get used to writing and using model_instance.get_absolute_url(). Personally I'm using the latter whenever possible, adding also custom "URL functions" like get_delete_url() etc.