wildfish / django-star-ratings

Star ratings for your Django models with a single template tag. Python 3 compatible.
Other
299 stars 97 forks source link

How Do I Use this app with jinja2 Tempalte?? #59

Open taedori81 opened 8 years ago

taedori81 commented 8 years ago

How Do I Use this app with jinja2 Tempalte??

How can I do that?

Like {% load ratings %} doesn't exist in jinja2

OmegaDroid commented 8 years ago

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/.

mrdumpty commented 5 years ago

The way to make it work in jinja2 template is below. You can add this to the docs.

1) 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) }}
...