Modify the jinja2 variable identifier when using webpy
Override the render_jinja class in the template. py file in the webpy package.
Class my_render_jinja: "rendering interface to jinja2 templates example: render = render_jinja ('templates') render. hello (name = 'jinja2') "def _ init _ (self, * a, ** kwargs): extensions = kwargs. pop ('extension', []) globals = kwargs. pop ('globals', {}) from jinja2 import environment, filesystemloader self. _ lookup = environment (loader = filesystemloader (* a, ** kwargs), extensions = extensions) # Add the following code to modify the identifier self. _ lookup. variable_start_string = '{'self. _ lookup. variable_end_string = '}' self. _ lookup. globals. update (globals) def _ getattr _ (self, name): # assuming all templates end. HTML Path = Name + '.html't = self. _ lookup. get_template (PATH) return T. render
Is there any other way?
The variable identifier of jinja2 can be accessed through the following method, but cannot be modified
# You can access import jinja2jinja2 in the following ways. defaults. invalid # jinja2.defaults is invalid when values are assigned in the following method. variable_start_string = '{'jinja2. defaults. variable_end_string = '}' jinja2. environment. variable_start_string = '{'jinja2. environment. variable_end_string = '}}'
Why is it invalid?
The reason is that when jinja2 is imported, the _ init _. py file in the jinja2 package is executed, and the _ init _. py file is imported into the environment object.
The constructor _ init _ of the environment object (variable_start_string = variable_start_string, variable_end_string = variable_end_string,...) has the default value.
The default value is fixed when environment is imported and cannot be modified later.
Therefore, the assignment method is invalid.
After understanding the cause, you can find another method to set it before import.
_ Docformat _ = 'restructuredtext en' _ version _ = '2. 7.2 '# High Level interface # Add the following three codes to import defaultsdefaults. variable_start_string = '{'defaults. variable_end_string = '}' from role import environment, template # loadersfrom jinja2.loaders import baseloader, filesystemloader, packageloader, dictloader, functionloader, prefixloader, choiceloader, moduleloader
Modify the variable identifier in the jinja2 Template