2010-01-19 3 views
2

나는django 1.x와 통합 된 jinja2 템플릿 용 번역 문자열 가져 오기?

 
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) 

다음과 같이 정의에는 render_to_response를 통해 장고 템플릿을 jinj2 사용할 수 있지만 jinja2 템플릿에 대한 장고 추출물 번역 문자열을 만들 수 없습니다.

는 아래 선이 장고가 유틸은/번역/trans_real.py 이 가능 makemessages 있도록 더 좋은 방법이 [email protected]_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 템플릿에서 로컬 사용을 위해 regexes를 사용 하시겠습니까?

답변

2

기본 수정은 다음과 같습니다. 필요에 맞게 추가/수정해야 할 수도 있습니다.

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


후 다음과 같은 메시지를 만드는 트릭

 
$ ~/myproject/ > ./manage.py mymakemessages -l $LANGUAGE -e .jinja -v 2 
를 않습니다 호출 내 템플릿 templ_name.jinja로 명명되어

, 다음이 필요합니다 위의 명령에서 .jinja 을 템플릿 이름으로 사용하는 확장명으로 바꿉니다.

+0

은 또한 장고 완화 패키지했습니다 - 번역 문자열에 대한 지원, 신사 통합. https://github.com/altunyurt/djtemps – hinoglu

관련 문제