我对本地化站点使用两种机制: 1. 我在 index.html 中使用标准模板标签 {{ gettext 'some_text'}} 2. 我编写了自定义 jinja 扩展,它根据使用的语言获取 markdown 文件的内容地点。
我使用 Babel 创建 messages.pot 文件,然后创建 Massages.po 文件。
我在 babel.cfg 中有这个 babel 配置:
[jinja2: theme/templates/index.html]
silent = false
这是我的自定义 jinja 扩展 - custom_jinja_extension.py :
from jinja2 import nodes
from jinja2.ext import Extension
from markdown import Markdown
class IncludeMarkdownExtension(Extension):
"""
a set of names that trigger the extension.
"""
tags = set(['include_markdown'])
def __init__(self, environment):
super(IncludeMarkdownExtension, self).__init__(environment)
def parse(self, parser):
tag = parser.stream.__next__()
ctx_ref = nodes.ContextReference()
if tag.value == 'include_markdown':
args = [ctx_ref, parser.parse_expression(), nodes.Const(tag.lineno)]
body = parser.parse_statements(['name:endinclude_markdown'], drop_needle=True)
callback = self.call_method('convert', args)
return nodes.CallBlock(callback, [], [], body).set_lineno(tag.lineno)
def convert(self, context, tagname, linenum, caller):
"""
Function for converting markdown to html
:param tagname: name of converting file
:return: converting html
"""
for item in context['extra_siteurls']:
if item == context['main_lang']:
input_file = open('content/{}/{}'.format('en', tagname))
else:
input_file = open('content/{}/{}'.format(context['main_lang'], tagname))
text = input_file.read()
html = Markdown().convert(text)
return html
我使用这个模板标签 -{% include_markdown 'slide3.md' %}{% endinclude_markdown %}
在我的 pelicanconf.py 中,我为 jinja 扩展添加了这样的字符串:
# Jinja2 extensions
JINJA_ENVIRONMENT = {
'extensions': [
'jinja2_markdown.MarkdownExtension',
'jinja2.ext.i18n',
'custom_jinja_extension.IncludeMarkdownExtension'
]
}
当我运行命令时:
pybabel extract --mapping babel.cfg --output messages.pot ./
我收到这个错误
jinja2.exceptions.TemplateSyntaxError:遇到未知标签“include_markdown”。Jinja 正在寻找以下标签:'endblock'。需要关闭的最里面的块是“块”。
当我删除所有使用自定义模板标签时,gettext 效果很好。我做错了什么?