Code Monkey home page Code Monkey logo

jinja2-django-tags's Introduction

jinja2-django-tags

jinja2-django-tags on pypi

This little library contains extensions for jinja2 that add template tags to jinja2 that you are used to from django templates.

The following tags are included:

There is also an extension for localizing template variables.

Requirements

This library requires at least Django 1.8 because there official jinja2 support was added.

If you want to use jinja2 templates in older versions of Django, take a look at django-jinja.

This library has been tested on Python 2.7, 3.4 and 3.5, Jinja 2.7 and 2.8, and Django 1.8, 1.9 and 1.10.

Usage

To use the tags, just run setup.py install from the base directory or pip install jinja2-django-tags and add the extensions to your TEMPLATES settings:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'extensions': [
                'jdj_tags.extensions.DjangoStatic',
                'jdj_tags.extensions.DjangoI18n',
            ]
        },
    },
}

If you want all tags at once use jdj_tags.extensions.DjangoCompat in the extensions Option.

Tags

csrf_token

The {% csrf_token %} tag comes with jdj_tags.extensions.DjangoCsrf.

-----------------The i18n tags are defined in jdj_tags.extensions.DjangoI18n. The extension also tries to localize variables (such as dates and numbers) if USE_L10N is set in django settings.

{% trans %} works as it does in django:

Simple example: {% trans 'Hello World' %}

{% trans "I was saved to a variable!" as translated_var %}
Save to a variable: {{ translated_var }}

Translation with context:
{% trans 'Hello World' context 'second hello world example' %}

Noop translation: {% trans "Please don't translate me!" noop %}

{% blocktrans %} works as it does in django including with, trimmed, context, count and asvar arguments:

Simple example: {% blocktrans %}Hello World!{% endblocktrans %}

Variables:
{% url 'my_view' as my_url %}
{% blocktrans with my_upper_url=my_url|upper %}
    Normal url: {{ my_url }}
    Upper url: {{ my_upper_url }}
{% endblocktrans %}

Trim whitespace and save to variable:
{% blocktrans trimmed asvar translated_var %}
    Trim those
    pesky newlines.
{% endblocktrans %}
Translated text: {{ translated_var }}

You can also use _, gettext and pgettext directly:

Simple example: {{ _('Hello World') }}
More verbose: {{ gettext('Hello World') }}
With context: {{ pgettext('Hello World', 'another example') }}

now

The {% now %} tag comes with jdj_tags.extensions.DjangoNow. It works the same as in Django:

Current year: {% now 'Y' %}

{% now 'Y' as cur_year %}
Copyright My Company, {{ cur_year }}

static

The {% static %} tag comes with jdj_tags.extensions.DjangoStatic. It works the same as in Django:

My static file: {% static 'my/static.file' %}

{% static 'my/static.file' as my_file %}
My static file in a var: {{ my_file }}

url

The {% url %} tag is defined in jdj_tags.extensions.DjangoUrl. It works as it does in django, therefore you can only specify either args or kwargs:

Save to variable:
{% url 'my_view' 'foo' 'bar' as my_url %}
{{ my_url }}

Localization

The jdj_tags.extensions.DjangoL10n extension implements localization of template variables with respect to USE_L10N and USE_TZ settings:

>>> from datetime import datetime
>>> from django.utils import timezone, translation
>>> from jinja2 import Extension
>>> env = Environment(extensions=[DjangoL10n])
>>> template = env.from_string("{{ a_number }} {{ a_date }}")
>>> context = {
...     'a_number': 1.23,
...     'a_date': datetime(2000, 10, 1, 14, 10, 12, tzinfo=timezone.utc),
... }
>>> translation.activate('en')
>>> timezone.activate('America/Argentina/Buenos_Aires')
>>> template.render(context)
'1.23 Oct. 1, 2000, 11:10 a.m.'
>>> translation.activate('de')
>>> translation.activate('Europe/Berlin')
>>> template.render(context)
'1,23 1. Oktober 2000 16:10'

jinja2-django-tags's People

Contributors

alexpirine avatar moritzs avatar pablosichert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

jinja2-django-tags's Issues

blocktrans is not compatible with Jinja2 version 3+

Hi.
When I updated jinja2 verion 3, templates using blocktrans started failing:

from django.template import engines
env = engines.all()[0].env
env.from_string("{% blocktrans %}test.key{% endblocktrans %}")

raises an error

Error
Traceback (most recent call last):
  File "/opt/project/tests/test_helpers.py", line 203, in test_without_nulls
    template = self.env.from_string("{% blocktrans %}test.key{% endblocktrans %}")
  File "/app/pip/lib/python3.10/site-packages/jinja2/environment.py", line 1092, in from_string
    return cls.from_code(self, self.compile(source), gs, None)
  File "/app/pip/lib/python3.10/site-packages/jinja2/environment.py", line 757, in compile
    self.handle_exception(source=source_hint)
  File "/app/pip/lib/python3.10/site-packages/jinja2/environment.py", line 925, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<unknown>", line 1, in template
jinja2.exceptions.TemplateSyntaxError: unexpected end of template, expected 'end of statement block'.

Pluralize and multiple language forms

Hi.
I may have misunderstood something, but I can't make it working.
In russian language nouns are pluralized into 4 forms, not 2. Example:

{% blocktrans count counter=stats['users_count'] %}Уникальный посетитель{% plural %}Уникальные посетители{% endblocktrans %}

And .po file:

#: apps/jinja2/emails/app_stats_email.jinja2:348
msgid "Уникальный посетитель"
msgid_plural "Уникальные посетители"
msgstr[0] "Уникальный посетитель"
msgstr[1] "Уникальных посетителя"
msgstr[2] "Уникальных посетителей"

If I understood correctly, django's template pluralization should output one of msgstr[0] - msgstr[2] depending on the counter. But it always outputs msgid_plural.

Possible integration with django-jinja

Hi!

I'm a django-jinja developer and maintainer.

First of all, great work. I thinking that it make sense join forces and integrate that into django-jinja directly. If you are interested we can talk how we can colaborate.

Making this extensions easy available for all versions of django, not only django 1.8.

That do you thing about?

Lifesaver!

You should ping coffin to use those. Special thanks for the fact that you've implemented the pgettext with blocktrans context.

I'm now replacing my jinja2 trans tags with this because jinja2 doesn't support context...

{% blcktrans %} not working with plural forms

Template:

{% blocktrans count candy_num=4 %}
  {{ candy_num }} candy
{% plural %}
  {{ candy_num }} candies
{% endblocktrans %}

Result:

'candy_num' is undefined

In extensions.py, things seem to get wrong at line 266:

            if context is None:
                return ugettext(force_text(singular)) % trans_vars
            else:
                return pgettext(force_text(context), force_text(singular)) % trans_vars
        else:
            if context is None:
                return ungettext(
                    force_text(singular), force_text(plural), trans_vars[count_var] # errorneous
                ) % trans_vars
            else:
                return npgettext(
                    force_text(context), force_text(singular), force_text(plural),
                    trans_vars[count_var]
                ) % trans_vars

Local vars:

Variable Value
context None
count_var 'candy_num'
plural Markup('\n %(candy_num)s candies\n')
self <jdj_tags.extensions.DjangoCompat object at 0x…>
singular Markup('\n %(candy_num)s candy\n')
trans_vars {'candy_num': Undefined}

Localizing dates in templates

Hi.
I'm not understanding, how date region dependent localization works.

  1. Is it like django {{ date|localize }} ? I always get isoformat now, my FORMAT_MODULE_PATH is ignored,
  2. If I want to get localized date, what should I activate? translation.activate('ru')? or timezone.activate(...) or both?
    Thanks

{% trans 'key' %} raises AttributeError

Hi.
I use gunicorn server served by supervisor (in venv). When I reboot supervisor code is updated.
But when I cleanly install django-jinja on the server via pip and release project version with django-jinja included libs, I get an error:
("expected token 'name', got 'string'",)
in jinja2 templates on statements like:
{% trans 'panel.emails.password_reset.link_valid_interval' %}
After some time, the error is gone (some sort of caching?) and never occures again. The error can at the same time appear on one template and don't appear on another one.
I've tried deleting pycache directory in all project directories, but it didn't resolve the issue.
image

Question about implementing Django-style tag

Hi! I am switching from Django templates to Jinja and trying to write my own Extensions, by studying your code in extensions.py. Thank you for providing this guide.

I have a tag that takes 1 required positional arg and 1 optional kwarg:

{% form_field 'age' label='how old are you?' %}.

I know that in Jinja this should be a macro like {% form_field('age', label='how old are you?') %}, but for compatibility I need to preserve the old Django-style syntax.

I am wondering about the simplest way to implement this? Because this template tag is just like a python function with 2 args (no special syntax or custom keywords like with, as, etc).

Or do I need to parse the tokens one by one, check if each is TOKEN_STRING, TOKEN_NAME, etc.? Although I read your code, I am not sure how to deal with the case where the args are context variables, e.g.:

context = {'field_name': 'age', 'label': 'How old are you?'}

{% form_field field_name label=label %}.

Any advice? Thank you so much.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.