获取与 django 1.x 集成的 jinja2 模板的翻译字符串?

发布于 2024-08-18 03:54:44 字数 2109 浏览 6 评论 0原文

我可以通过如下定义的 render_to_response 将 jinj2 模板与 django 一起使用,

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 命令可以通过 templatize@trans_real.py 解析 i18n 的 django 模板

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"""_\(((?:".*?")|(?:'.*?'))\)""")

有没有比通过重写翻译标签正则表达式以在 jinja2 模板上本地使用来提取翻译字符串来修改 makemessages.py 更好的方法?

I can use jinj2 templates with django via render_to_response defined as below

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)

but cannot make django extract translation strings for jinja2 templates.

seems that the lines below in django/utils/translation/trans_real.py
make it possible for makemessages command to parse django templates for i18n via 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"""_\(((?:".*?")|(?:'.*?'))\)""")

is there a nicer way than modifying the makemessages.py by rewriting translation tags regexes for local use on jinja2 templates to extract translation strings?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森罗 2024-08-25 03:54:44

对我来说做了一点修改。基本配方如下,
您可能需要添加/修改更多内容以满足您的需求。

$ ~ > 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
在上面的命令中使用您用于模板名称的任何扩展名。

A little modification made it for me.. Base recipe is as follows,
you might need to add/modify some more to fit your needs.

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

and make the modifications given below:

$ ~ > 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'))


then calling make messages as follows does the trick

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

my templates are named as templ_name.jinja, you'll need to replace .jinja
in the command above with whatever extension you use for your template names.

情绪少女 2024-08-25 03:54:44

我已根据以下方法向 Coffin 添加了对此的支持:

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

I've added support for this to Coffin, based on this approach:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文