django-star-ratings
django-star-ratings copied to clipboard
How Do I Use this app with jinja2 Tempalte??
How Do I Use this app with jinja2 Tempalte??
How can I do that?
Like {% load ratings %} doesn't exist in jinja2
We haven't written a jinja extension for this yet. If you wanted to write one we would be happy to accept the pull request.
This link may be useful http://jinja.pocoo.org/docs/dev/extensions/.
The way to make it work in jinja2 template is below. You can add this to the docs.
- As you can see here:
Using context processors with Jinja2 templates is discouraged. Context processors are useful with Django templates because Django templates don’t support calling functions with arguments. Since Jinja2 doesn’t have that limitation, it’s recommended to put the function that you would use as a context processor in the global variables available to the template using jinja2.Environment as described below. You can then call that function in the template:
So, I suppose you've configured your jinja2 environment as described there
Well, lets modify this base example a little to add ratings tag:
In yourproject/jinja2.py:
from django.templatetags.static import static
from django.urls import reverse
from jinja2 import Environment, contextfunction
from star_ratings.templatetags.ratings import ratings
@contextfunction
def get_context(c):
return c
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': static,
'url': reverse,
'context': get_context,
'ratings': ratings,
})
return env
Thats all! Now you can use ratings in your jinja2 templates, just simply:
...
{{ ratings(context(), object) }}
...