Setup Jinja2 in Django Project - django

Newbie question, yet I cannot find a sufficient step-by-step instruction on Jinja2 official website or by googling.
My current Django project is halfway done, and I cannot stand not able to use queryset filter in Django template anymore. So decide to switch to Jinja2.
What I have done: pip install jinja2 to the virtualenv. Then I tried to use Jinja syntax in my template files, which fails.. apparently and sadly
What else do I need to do to make Jinja2 work?

I just want to recommend two alternatives I find very useful.
Jinja template tag
One is the jinja template tag which lets you use jinja within django templates as
{% jinja %}{{ this_is_jinja(True)}}{% endjinja %}
Very useful when you can't / don't want to break the rest of your existing templates.
http://www.mellowmorning.com/2010/08/24/mixing-django-with-jinja2-without-losing-template-debugging/
Conditional template engine
The other is conditional loading of template engines based on filename (note I wrote this since I use both template languages):
https://github.com/yuchant/django-jinja2

You'll need to switch to using a rendering method that uses Jinja2 templates instead of Django templates - coffin has a helper you can use named render_to_response that should work.

Related

How can I load a module in a Django template with a variable for the module name?

I want to build some very similar apps in Django, but I want them to load different tag/filter modules. For this I want the html templates to be generic. For example, I would like to have something like
{% load specific_tags %}
and then I would like to define the variable specific_tags in a context processor for each app. But Django thinks that it should look for "specific_tags" in the installed apps in settings.py. How can I tell Django/Python to first evaluate the content of the variable from the context processor?
Best regards
Why don't you simply put this values in setting files, this is the way how I am differentiating between dev, test, demo and production environments, and the use one of the solution found here to load that value sin your template:
Can I access constants in settings.py from templates in Django?

Can you use two HTML templates such as Handlebars and Jinja

I'm trying to write an app in javascript with the ember.js library which relies heavily on the Handlebars templating system. However, I'm using FLASK which also uses the jinja templating system.
Is it possible to use both template renderers at the same time? Or do I need to use one over another. Anyone with experience using both flask and ember.js know which one would potentially be easier to replace with the other?(Maybe handlebars is much easier to replace Jinja with or vice versa).
Note that these two template engines are in different places. Jinja2 will run on the server side, Handlebars will run on the client side. You could potentially use both without interference if you needed to.
But with that said, there is really no need to use server-side templates if you have a rich client framework like ember.js. In your situation the Flask server will likely have routes that serve data via ajax requests back to the ember.js client, so the client is really the best place for template rendering to happen.
You can mark sections of code as {% raw %} to tell jinja2 to ignore it. Wrap your handlebars.js template in raw tags like so:
{% raw %}
<script id="foo-template" type="text/x-handlebars-template">
<p>{{foo}} - {{bar}}</p>
</script>
{% endraw %}
As #Miguel said, you don't really need Jinja2 if your using ember.js, I figured out if you don't want to render those templates, simply return flask.send_file('your html file here') instead returning flask.render_template('your html file here'). See the docs for more details.
While I fundamentally agree with both #Miguel and #Ali, several companies I have worked with mix the RESTful model for APIs with server-generated HTML. [NOTE: This shouldn't be the case when using Ember, but I'm working with Flask / Jinja2 and Backbone in my current client's code base.]
I actually found a solution using Pybars, based on some reading from Khan Academy's style guide:
#app.template_filter("handlebars")
def handlebars_filter(context, filepath):
source = open( filepath, "r").read().decode('utf-8')
template = pybars.Compiler().compile( source )
return Markup( u"".join( template( context )))

Accessing session value in django template

I am setting
request.session['total_items'] = 3
in a views.py file of a django app
in template
i got to know that you can access it as {{request.session.total_items}}
Everything is fine and i'm able to get the value.
However,my question is that why it is not {{request.session['total_items']}} instead, since request.session is a dictionary like object.
For {{request.session['total_items']}}, its giving an error as following:
Could not parse the remainder: '['total_items']' from 'request.session['total_items']'
Any help would be appreciated ...
Do not confuse Django template language with Python Syntax. Django template language its a language on its own and have its own way of performing things. As doc suggests:
The goal is not to invent a programming language. The goal is to offer
just enough programming-esque functionality, such as branching and
looping, that is essential for making presentation-related decisions.
When you have enabled the django.core.context_processors.request it will enable the access to the values of a dictionary-like objects with the . notation.
This will convert any Python object into something that the Django template language will understand as it is its own language.
This also applies for the following:
Attribute lookups (eg. myobject.age)
Method calls (eg. myobject.age())
List indices (eg mylist.1)
The thing that is working it behind the scenes is the Context object.
You can read more on how it works here and here
And you can compare the Python controlstructure if to Django's template language.
if object:
myobject.dostuff()
to
{% if object %}
{{ myobject.dostuff }}
{% endif %}
If you want a closer match to Python you should check out
Jinja2
PyHAML

Assigning Backbone templates using Django pipeline similar to Rails JST?

I'm building a large scale Backbone Marionette app on top of Django utilizing the Django asset pipeline to compile all of the assets.
Right now, I am saving my Handlebars templates as JS strings in the app object like so:
App.Templates.Header = '
<div id="header">
... header stuff ...
</div>
'
class App.Views.Header extends Backbone.Marionette.ItemView
template: App.Templates.Header
I'm not sure that saving templates out into JS strings is really the best way to do things at all. With Rails, you can save out template files and reference them directly in the file structure with JST:
template: JST['apps/base/templates/header']
My understanding is that this is a feature that is baked in to Rails. Is something like this possible with Django? Or, is there another more efficient way that I should be handling my templates?
This features is actually built into Django Pipeline under as JavaScript Templates.
Basically, you define the function to use for processing your templates (Mustache, Handlebars, Prototype or JST) and then the global namespace where those templates are stored and the extension that the compiler uses to determine which files to add to that template object.

Django template tag to determine "a" or "an"

Is there an existing django template tag to determine a/an before an article? If not, how would I go about writing such a tag?
Someone was kind enough to leave a snippet here: http://djangosnippets.org/snippets/1519/
There's a nice pip package, anora, that will add this template tag for you without having to maintain the code in your own app.