Получение строк перевода для шаблонов jinja2, интегрированных с django 1.x? - PullRequest
3 голосов
/ 19 января 2010

Я могу использовать шаблоны jinj2 с django через render_to_response, определенный как ниже

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.template import TemplateDoesNotExist, Context
from django.utils import translation
from itertools import chain
from jinja2 import FileSystemLoader, Environment
from jinja2 import nodes
from jinja2.ext import Extension 
from django.conf import settings

import jinja_filters as jf
import traceback

from django.utils.translation import gettext, ngettext

class DjangoTranslator(object):

    def __init__(self):
        self.gettext = gettext
        self.ngettext = ngettext

class DjangoEnvironment(Environment):

    def get_translator(self, context):
        return DjangoTranslator()


template_dirs = getattr(settings,'TEMPLATE_DIRS')
default_mimetype = getattr(settings, 'DEFAULT_CONTENT_TYPE')
global_exts = getattr(settings, 'JINJA_EXTENSIONS', ())
env = DjangoEnvironment(autoescape=False, loader=FileSystemLoader(template_dirs, encoding="utf-8"), extensions=global_exts)
env.filters.update({'myescape':jf.myescape})

if 'jinja2.ext.i18n' in global_exts:
        env.install_gettext_translations(translation)

def render_to_response(filename, context={}, context_instance=Context({}), mimetype=default_mimetype):
    template = env.get_template(filename)
    for d in context_instance.dicts:
        context.update(d)
    context.update({'settings':settings})
    rendered = template.render(**context)
    return HttpResponse(rendered, mimetype=mimetype)

, но не может заставить django извлекать строки перевода для шаблонов jinja2.

кажется, что строки ниже в django / utils / translation / trans_real.py позволяет команде makemessages анализировать шаблоны django для i18n через templatize@trans_real.py

inline_re = re.compile(r"""^\s*trans\s+((?:".*?")|(?:'.*?'))\s*""")
block_re = re.compile(r"""^\s*blocktrans(?:\s+|$)""")
endblock_re = re.compile(r"""^\s*endblocktrans$""")
plural_re = re.compile(r"""^\s*plural$""")
constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?'))\)""")

Есть ли более приятный способ, чем модифицировать makemessages.py, переписывая регулярные выражения тегов перевода для локального использования в шаблонах jinja2 для извлечения строк перевода?

Ответы [ 2 ]

2 голосов
/ 20 января 2010

Небольшая модификация сделана для меня. Базовый рецепт выглядит следующим образом, вам может потребоваться добавить / изменить еще несколько, чтобы соответствовать вашим потребностям.

$ ~ > cp $DJANGO_PATH/utils/translation/ myproject/utils/ -a

и внести следующие изменения:

$ ~ > diff $DJANGO_PATH/utils/translation/trans_real.py myproject/utils/translation/trans_real.py  -u

--- utils/translation/trans_real.py     Wed Jan 20 05:07:46 2010
+++ myproject/utils/translation/trans_real.py    Wed Jan 20 04:51:39 2010
@@ -435,6 +435,9 @@
 endblock_re = re.compile(r"""^\s*endblocktrans$""")
 plural_re = re.compile(r"""^\s*plural$""")
 constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?'))\)""")

+jinja_block_re = re.compile(r"""^\s*trans(?:\s+|$)""")
+jinja_endblock_re = re.compile(r"""^\s*endtrans$""")

 def templatize(src):
     """
@@ -451,7 +454,7 @@
     for t in Lexer(src, None).tokenize():
         if intrans:
             if t.token_type == TOKEN_BLOCK:
-                endbmatch = endblock_re.match(t.contents)
+                endbmatch = jinja_endblock_re.match(t.contents)
                 pluralmatch = plural_re.match(t.contents)
                 if endbmatch:
                     if inplural:
@@ -485,7 +488,7 @@
         else:
             if t.token_type == TOKEN_BLOCK:
                 imatch = inline_re.match(t.contents)
-                bmatch = block_re.match(t.contents)
+                bmatch = jinja_block_re.match(t.contents)
                 cmatches = constant_re.findall(t.contents)
                 if imatch:
                     g = imatch.group(1)


$ ~ > cp $DJANGO_PATH/core/management/commands/makemessages.py myproject/myapp/management/commands/ 


$ ~/myproject/ > diff  $DJANGO_PATH/core/management/commands/makemessages.py main/management/commands/makemessages.py -u
--- /usr/lib/python2.5/site-packages/django/core/management/commands/makemessages.py    Wed Jan 20 05:08:37 2010
+++ main/management/commands/makemessages.py    Wed Jan 20 05:28:41 2010
@@ -56,7 +56,7 @@
     else:
         settings.configure(USE_I18N = True)

-    from django.utils.translation import templatize
+    from myproject.utils.translation import templatize

     if os.path.isdir(os.path.join('conf', 'locale')):
         localedir = os.path.abspath(os.path.join('conf', 'locale'))


затем вызов команды make messages делает трюк

$ ~/myproject/ > ./manage.py mymakemessages -l $LANGUAGE -e .jinja -v 2

мои шаблоны называются templ_name.jinja, вам нужно заменить .jinja в приведенной выше команде на любое расширение, которое выиспользуйте для ваших имен шаблонов.

1 голос
/ 27 февраля 2010

Я добавил поддержку для Coffin, основываясь на этом подходе:

http://github.com/miracle2k/coffin/commit/ba1a8a510b05074731d383e0dc1f7c21c67ff728

...