【问题标题】:Unexptected '%' rendering a Jinja2 template呈现 Jinja2 模板时出现意外的“%”
【发布时间】:2019-06-15 21:59:58
【问题描述】:

所以,基本上我正在运行一个生成一些文件的 python 脚本。问题是:每个 .cpp 和 .hpp 文件的生成都没有问题,而脚本抛出异常生成 CMakeLists.txt,这是一个奇怪的:

Traceback (most recent call last):
File "enum_generator.py", line 115, in <module>
  generate_cmakelists(result)
File "enum_generator.py", line 98, in generate_cmakelists
  'templates/cmakelists_enums_template.jinja2', result=result)
File "enum_generator.py", line 43, in render_to_file
  jinja_template = Template(template_file)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 945, in __new__
  return env.from_string(source, template_class=cls)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 880, in from_string
  return cls.from_code(self, self.compile(source), globals, None)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 591, in compile
  self.handle_exception(exc_info, source_hint=source_hint)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
  reraise(exc_type, exc_value, tb)
File "<unknown>", line 8, in template
jinja2.exceptions.TemplateSyntaxError: unexpected '%'

我尝试了相同的代码,使用 .cpp 和 .hpp 文件的模板,它运行良好。下面你可以看到 CMake_template 和 python 脚本

cmake_minimum_required(VERSION 3.0.0)
project(ART_Plugin_Enums)

set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})

add_library(ART_Plugin_Enums ${LIBRARY_TYPE}
                        {% for category in result.keys() -%}
                    enums/{{category}}Enum.hpp

                    inc/{{category}}EnumPlugin.hpp
                    inc/{{category}}EnumPlugin_module.hpp

                    src/{{category}}EnumPlugin.cpp
                    src/{{category}}numPlugin_module.cpp
                    {%endfor%})

这是脚本:

def render_to_file(target_file_path, template_name, *args, **kwargs):
    with open(target_file_path, 'w+') as f:
        template_file = open(os.path.join(SCRIPT_LOCATION,
                                          template_name)).read()
        jinja_template = Template(template_file)
        print("-- Generating {}".format(target_file_path))
        f.write(jinja_template.render(*args, **kwargs))


def generate_cmakelists(result):
    target_file_path = os.path.join(SCRIPT_LOCATION, '..', "CmakeLists.txt")
    return render_to_file(
        target_file_path,
        'templates/cmakelists_enums_template.jinja2', result=result)

generate_cmakelists(result)

我很困惑,因为我不明白为什么 Jinja 没有识别出 for 中的 %。有什么线索吗?

【问题讨论】:

  • 因为前面的-?
  • {% for category in result.keys() -%} 更改为{% for category in result.keys() %}
  • 同样的错误,在其他功能模板中也是一样的,他们工作了

标签: python jinja2 code-generation


【解决方案1】:

实际上,我认为我打开的文件太多,并且在编辑与正在渲染的文件不同的文件时搞砸了。抱歉让您耽误了时间,代码确实有效。

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2013-05-12
    • 2014-03-28
    • 1970-01-01
    相关资源
    最近更新 更多